Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore RoboGarden C++

RoboGarden C++

Published by bassem.abdullah, 2016-02-22 13:02:32

Description: RoboGarden C++

Search

Read the Text Version

Table of ContentsTABLE OF CONTENTS ..........................................................................................................................................................IABOUT THIS MANUAL.................................................................................................ERROR! BOOKMARK NOT DEFINED.NOTES .............................................................................................................................................................................. IV1 GETTING STARTED ................................................................................................................................................11.1 ENVIRONMENT SETUP ...........................................................................................................................................1 1.1.1 Making Your First Program Bricx Command Center .......................................................................................1 1.1.2 First Program ....................................................................................................................................................21.2 PROGRAM STRUCTURE...........................................................................................................................................32 VARIABLES , CONSTANTS , DATA TYPES ........................................................................................................52.1 DATA TYPES...........................................................................................................................................................5 2.1.1 Defining variables.............................................................................................................................................5 2.1.2 Variable Definition in C: ..................................................................................................................................6 2.1.3 Variable Declaration in C: ................................................................................................................................6 Example (1) ............................................................................................................................................................................. 7 Comments......................................................................................................................................................................7 Example (2) ............................................................................................................................................................................. 7 2.1.3.1 Then how would we know if a data type is sufficient to represent a number or not .................................................7 2.1.4 Integer Types ....................................................................................................................................................7 2.1.5 Floating-Point Types.........................................................................................................................................8 2.1.6 Constants...........................................................................................................................................................8 2.1.7 Integer literals ...................................................................................................................................................8 2.1.8 Floating-point literals........................................................................................................................................9 2.1.9 Character Constants ..........................................................................................................................................9 2.1.10 String literals...............................................................................................................................................10 2.1.11 Defining Constants .....................................................................................................................................10 2.1.12 The #define Preprocessor............................................................................................................................10 2.1.13 The const Keyword.....................................................................................................................................112.2 C - OPERATORS....................................................................................................................................................11 2.2.1 Arithmetic Operators ......................................................................................................................................11 2.2.2 Relational Operators .......................................................................................................................................12 2.2.3 Logical Operators ...........................................................................................................................................12 2.2.4 Bitwise Operators ...........................................................................................................................................12 2.2.5 Assignment Operators.....................................................................................................................................133 DECISION MAKING ...............................................................................................................................................153.1 IF...ELSE STATEMENT ...........................................................................................................................................15 3.1.1 Syntax .............................................................................................................................................................15 Example (1) ........................................................................................................................................................................... 16 Example (2) ........................................................................................................................................................................... 173.2 C - SWITCH STATEMENT .......................................................................................................................................17 3.2.1 Syntax .............................................................................................................................................................17 Example (3) ........................................................................................................................................................................... 183.3 CONDITIONAL OPERATORS (( ? : ) OPERATOR ) ...................................................................................................194 LOOPS .......................................................................................................................................................................204.1 LOOP CONTROL STATEMENTS: ............................................................................................................................204.2 FOR LOOP.............................................................................................................................................................214.2.1 Syntax: ............................................................................................................................................................214.2.2 How for loop works in C programming? ........................................................................................................214.3 WHILE LOOP ........................................................................................................................................................234.3.1 Syntax: ............................................................................................................................................................234.4 DO ..WHILE LOOP..................................................................................................................................................254.4.1 Syntax: ............................................................................................................................................................254.5 NESTED LOOP ......................................................................................................................................................264.5.1 Syntax: ............................................................................................................................................................264.6 BREAK STATEMENT..............................................................................................................................................27BREAK IS USED IN TERMINATING THE LOOP IMMEDIATELY AFTER IT IS ENCOUNTERED. THE BREAK STATEMENTIS USED WITH CONDITIONAL IF STATEMENT. ..............................................................................................................274.6.1 Syntax .............................................................................................................................................................27SoftProduct Name of Class 2011 – mm/ddTable of Contents Page i

4.7 CONTINUE STATEMENT ....................................................................................................................................... 28 4.7.1 Syntax: ............................................................................................................................................................ 28 4.8 ............................................................................................................................................................................ 28 4.9 ................................................................................................................................................................................... 28 4.10................................................................................................................................................................................. 28 4.11................................................................................................................................................................................. 28 4.12................................................................................................................................................................................. 28 4.13................................................................................................................................................................................. 28 4.14................................................................................................................................................................................. 28 4.15 GOTO STATEMENT ............................................................................................................................................... 28 GOTO STATEMENT IS USED FOR ALTERING THE NORMAL SEQUENCE OF PROGRAM EXECUTION BY TRANSFERRING CONTROL TO SOME OTHER PART OF THE PROGRAM. ....................................................................... 28 4.15.1 Syntax:........................................................................................................................................................ 285 FUNCTIONS ............................................................................................................................................................. 29 5.1 TYPES OF C FUNCTIONS ....................................................................................................................................... 29 5.1.1 Library function .............................................................................................................................................. 29 5.1.2 User defined function ..................................................................................................................................... 29 5.1.2.1 How user-defined function works in C Programming?............................................................................................ 29 Example of user-defined function.......................................................................................................................................... 30 5.2 FUNCTION PROTOTYPE(DECLARATION): .............................................................................................................. 30 5.2.1 Syntax of function prototype .......................................................................................................................... 30 5.3 FUNCTION CALL................................................................................................................................................... 30 5.3.1 Syntax of function call.................................................................................................................................... 31 IN THE ABOVE EXAMPLE, FUNCTION CALL IS MADE USING STATEMENT ADD(NUM1,NUM2); FROM MAIN(). THIS MAKE THE CONTROL OF PROGRAM JUMP FROM THAT STATEMENT TO FUNCTION DEFINITION AND EXECUTES THE CODES INSIDE THAT FUNCTION............................................................................................................................. 31 5.4 FUNCTION DEFINITION ......................................................................................................................................... 31 5.4.1 Syntax of function definition .......................................................................................................................... 31 5.4.2 Function declarator ......................................................................................................................................... 31 5.4.2.1 Syntax of function declarator................................................................................................................................... 31 5.4.3 Function body ................................................................................................................................................. 31 5.5 PASSING ARGUMENTS TO FUNCTIONS .................................................................................................................. 31 5.6 RETURN STATEMENT........................................................................................................................................... 32 5.6.1 Syntax of return statement .............................................................................................................................. 32 5.7 TYPES OF USER-DEFINED FUNCTIONS IN C PROGRAMMING................................................................................. 32 5.8 RECURSION.......................................................................................................................................................... 32 Example of recursion in C programming............................................................................................................................... 32 Example 1 .............................................................................................................................................................................. 33 Example 2 .............................................................................................................................................................................. 346 ARRAY AND STRING ............................................................................................................................................ 35 6.1 DECLARING ARRAYS ........................................................................................................................................... 35 6.1.1 Array elements................................................................................................................................................ 35 6.1.2 Initializing Arrays........................................................................................................................................... 35 6.1.3 Accessing Array Elements.............................................................................................................................. 35 6.2 ARRAYS AND FUNCTIONS .................................................................................................................................... 36 6.2.1 Passing Array In Function .............................................................................................................................. 37 SINGLE ELEMENT OF AN ARRAY CAN BE PASSED IN SIMILAR MANNER AS PASSING VARIABLE TO A FUNCTION . 37 Example ................................................................................................................................................................................. 37 6.2.2 Passing entire array to a function.................................................................................................................... 37 Example ................................................................................................................................................................................. 37 6.3 MULTIDIMENSIONAL ARRAYS ............................................................................................................................. 38 C PROGRAMMING LANGUAGE ALLOWS PROGRAMMER TO CREATE ARRAYS OF ARRAYS KNOWN AS MULTIDIMENSIONAL ARRAYS. FOR EXAMPLE: ........................................................................................................... 38 6.3.1 Initialization of Multidimensional Arrays ...................................................................................................... 38 Example of Multidimensional Array ..................................................................................................................................... 39 6.4 STRING ................................................................................................................................................................ 39 6.4.1 Defining strings .............................................................................................................................................. 39 6.4.2 Passing Strings to Functions ........................................................................................................................... 40 6.4.3 String Manipulations In C Programming Using Library Functions................................................................ 407 POINTERS ................................................................................................................................................................ 42 7.1 REFERENCE OPERATOR (&) ................................................................................................................................. 42 7.2 WHAT ARE POINTERS? ........................................................................................................................................ 42 Example To Demonstrate Working of Pointers ..................................................................................................................... 42Page ii SoftProduct Name of Class2011 – mm/dd Table of Contents

Explanation of program and figure ........................................................................................................................................ 43 7.3 POINTER ARITHMETIC ..........................................................................................................................................44 7.3.1 Incrementing a Pointer ....................................................................................................................................44 7.4 POINTERS AND ARRAYS .......................................................................................................................................44 7.4.1 Relation between Arrays and Pointers ............................................................................................................45 7.5 PASSING POINTERS TO FUNCTIONS IN C................................................................................................................45 Example of Pointer And Functions ........................................................................................................................................ 45 Example ................................................................................................................................................................................. 46 7.6 DYNAMIC MEMORY ALLOCATION .......................................................................................................................46 7.6.1 malloc()...........................................................................................................................................................47 7.6.1.1 Syntax of malloc().................................................................................................................................................... 47 7.6.2 calloc() ............................................................................................................................................................47 7.6.2.1 Syntax of calloc() ..................................................................................................................................................... 47 7.6.3 free() ...............................................................................................................................................................47 7.6.3.1 syntax of free() ......................................................................................................................................................... 47 Examples of calloc() and malloc() ......................................................................................................................................... 47 7.6.4 realloc()...........................................................................................................................................................48 7.6.4.1 Syntax of realloc().................................................................................................................................................... 488 STRUCTURES AND UNIONS ................................................................................................................................49 8.1 STRUCTURES........................................................................................................................................................49 8.1.1 Defining a Structure........................................................................................................................................49 8.1.2 Accessing Structure Members ........................................................................................................................49 8.1.3 Structures as Function Arguments ..................................................................................................................50 8.1.4 Pointers to Structures ......................................................................................................................................53 Example to access structure's member through pointer.......................................................................................................... 54 8.2 UNIONS................................................................................................................................................................55 8.2.1 Accessing members of an union .....................................................................................................................56 8.3 DIFFERENCE BETWEEN UNION AND STRUCTURE...................................................................................................56 Output .................................................................................................................................................................................... 56SoftProduct Name of Class 2011 – mm/ddTable of Contents Page iii

NotesSoftProduct Name of Class 2011 – mm/ddPreface Page iv

1 Getting Started1.1Environment SetupC programs consist of lines of text “Code”. Those lines contain state-ments/instructions telling the computer what to do. The order of the lines in the pro-gram is the same order in which the lines are read and executed by the computer.Following example shows a very simple C program1.1.1 Making Your First Program Bricx Command CenterMake sure you are installing Bricx Command Center correctly. 1. Connect Brick to your Computer 2. Start Bricx Command Center 3. Choose (usb,EV3,linux) 4. Open menu item File/New. 2011 – mm/dd 5. Write the above code Page 1 6. Save the file with the name of “main.c” in new folderSoftProduct Name of ClassTraining Manual

7. Open menu item View/Project Manger.8. Click right in the white area then click add9. Choose from API folder ev3_command.c and ev3_lcd.c and ev3_timer.c10.Open menu item File/Open main.prj 11.Complete the path of the c files 12.Save everything then click ctrl+F5 to Dawnlaod and RunThe Output in the Brick Screen1.1.2 First ProgramNow, for some explanations about the program itself. A C program, whatever its size,consists offunctionsand variables. A function contains statements that specify the computingoperations to be done, and variables store values used during the computation. Cfunctions are like the subroutines and functions in Fortran or the procedures andfunctions of Pascal. Our example is a function named main. Normally you are atliberty to give functions whatever names you like, but ``main'' is special – your2011 – mm/dd SoftProduct Name of ClassPage 2 Training Manual

program begins executing at the beginning of main. This means that every programmust have a main somewhere.mainwill usually call other functions to help perform its job, some that you wrote, andothers from libraries that are provided for you. The first lines of the program,tells the compiler to include information about LCD and Command libraries; the lineappears at the beginning of C source files.One method of communicating data between functions is for the calling function toprovide a list of values, called arguments, to the function it calls. The parenthesesafter the function name surround the argument list. In this example, main is definedto be a function that expects no arguments, which is indicated by the empty list ( ).The same is with LcdInit(), LcdExit()A function is called by naming it, followed by a parenthesized list of arguments, sothis calls thefunctionLcdTextwith the argument 1, 10, 10, \"I am alive!\". LcdTextis a function thatprints output on lcd, The first argument for choose the color of the text. 0 for whiteon black background.1 for black on white background. The second and the thirdargument are the x and y position of the screen.The 4th is for the output text. The same is with Wait funcition it take one argument isthe waiting time in seconds.1.2Program StructureA C program basically consists of the following parts: Preprocessor Commands Functions Variables Statements & Expressions CommentsSoftProduct Name of Class 2011 – mm/ddTraining Manual Page 3

1- Preprocessor Commands :- -Any Command that is preceded by (#)operator . -These commands will not compiled . 2- Functions is the basic element of any program , We will illustrate Functions later . 3-A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, We will describe variables later . 4- Comments in C :- 1-Singe line Comments ( // this is comment ) . 2-Multi line Comments (/* Comment 1 Comment 2 Comment 3 */ ) .// Getting Started Basic structure#include <stdio.h>// Preprocessor Command#include <iostream>// Preprocessor Command// Comment 1 -- Comment 2#define roboVics_Start 1 // Preprocessor Command#define roboVics_End 100 // Preprocessor Command/* Comment 3 -- Comment 4 Comment 5 */int add (int,int);// function prototype ;/* More Functions */int main (){ /* Main Program , Code Starts here */ // Statement 1 ; // Statement 2 ; // ..... ; //...... ; // ..... ; // Statement n ;}2011 – mm/dd SoftProduct Name of ClassPage 4 Training Manual

2 Variables , Constants , Data Types 2.1Data types C has several types of variables, but there are a few basic types:• Integers - whole numbers which can be both positive and negative. Defined us- ing char, int, short, long orlong long.• Unsigned integers - whole numbers which can only be positive. Defined using unsigned char, unsigned int,unsigned short, unsigned long or unsigned long long.• Floating point numbers - real numbers (numbers with fractions). Defined us- ing float and double.• Structures - will be explained later, in the Structures section. The different types of variables define their bounds. A char can range only from -128 to 127, whereas a long can range from -2,147,483,648 to 2,147,483,647. Note that C does not have a boolean type. usually, it is defined using the following notation: #define BOOL char #define FALSE 0 #define false 0 #define true 1 #define TRUE 1 2.1.1 Defining variables A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in previous chapter, there will be the following basic variable types:SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 5

2.1.2 Variable Definition in C: A variable definition means to tell the compiler where and how much to create thestorage for the variable. A variable definition specifies a data type and contains a list of oneor more variables of that type as followstypevariable_list;Here, type must be a valid C data type including char, w_char, int, float, double, bool or anyuser-defined object, etc., and variable_list may consist of one or more identifier names sep-arated by commas. Some valid declarations are shown here:int i, j, k;char c,ch;float f, salary;double d;The line int i, j, k; both declares and defines the variables i, j and k; which instructs the com-piler to create variables named i, j and k of type int.Variables can be initialized (assigned an initial value) in their declaration. The initializer con-sists of an equal sign followed by a constant expression as follows:typevariable_name= value;2.1.3 Variable Declaration in C:A variable declaration provides assurance to the compiler that there is one variable existingwith the given type and name so that compiler proceed for further compilation withoutneeding complete detail about the variable. A variable declaration has its meaning at thetime of compilation only, compiler needs actual variable declaration at the time of linking ofthe program.A variable declaration is useful when you are using multiple files and you define yourvariable in one of the files which will be available at the time of linking of the program. Youwill use extern keyword to declare a variable at any place. Though you can declare a variablemultiple times in your C program but it can be defined only once in a file, a function or ablock of code.2011 – mm/dd SoftProduct Name of ClassPage 6 Training Manual

Example (1)write a program that make the robot move forward for 5 second then stop. #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_output.h\" int main () { unsigned char speed = 100 ; int second = 1000; int time = 50 * second ; robotMotionInit(); robotForwardT (speed,time); robotMotionExit();Comments :- - speed has maximum value of 127 (See outputs appendix) . So a datatype of char issufficient to represent . -5000could be represented by integer ,but what about if we want to make the robot go forward for 50 Second ??Example (2) #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_output.h\" int main () { unsigned char speed = 100 ; unsigned int second = 1000; unsigned int time = 50 * second ; robotMotionInit(); robotForwardT (speed,time); robotMotionExit(); }Write a comment !!............................................................................................................................................................... .2.1.3.1 Then how would we know if a data type is sufficient to represent a number or not .2.1.4 Integer TypesFollowing table gives you details about standard integer types with its storage sizes andvalue ranges:Type Storage size Value range -128 to 127 or 0 to 255char 1 byte 0 to 255 -128 to 127unsigned char 1 byte -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 0 to 65,535 or 0 to 4,294,967,295signed char 1 byte -32,768 to 32,767 0 to 65,535Int 2 or 4 bytes -2,147,483,648 to 2,147,483,647unsigned int 2 or 4 bytes 2011 – mm/dd Page 7short 2 bytesunsigned short 2 byteslong 4 bytesSoftProduct Name of ClassTraining Manual

unsigned long 4 bytes 0 to 4,294,967,2952.1.5 Floating-Point TypesFollowing table gives you details about standard floating-point types with storage sizes andvalue ranges and their precision:Type Storage size Value range Precisionfloat 4 byte 1.2E-38 to 3.4E+38 6 decimal placesdouble 8 byte 2.3E-308 to 1.7E+308 15 decimal placeslong double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places2.1.6 ConstantsThe constants refer to fixed values that the program may not alter during its execution. These fixedvalues are also called literals.Constants can be of any of the basic data types like an integer constant, a floating constant, a char-acter constant, or a string literal. There are also enumeration constants as well.The constants are treated just like regular variables except that their values cannot be modified af-ter their definition.2.1.7 Integer literalsAn integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base orradix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,respectively. The suffix can be uppercase or lowercase and can be in any order.Here are some examples of integer literals:212/* Legal */215u/* Legal */0xFeeL/* Legal */078/* Illegal: 8 is not an octal digit */032UU/* Illegal: cannot repeat a suffix */Following are other examples of various type of Integer literals:85/* decimal */0213/* octal */0x4b/* hexadecimal */30/* int */30u/* unsigned int */30l/* long */30ul/* unsigned long */2011 – mm/dd SoftProduct Name of ClassPage 8 Training Manual

2.1.8 Floating-point literalsA floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.You can represent floating point literals either in decimal form or exponential form.While representing using decimal form, you must include the decimal point, the exponent, or bothand while representing using exponential form, you must include the integer part, the fractionalpart, or both. The signed exponent is introduced by e or E.Here are some examples of floating-point literals:3.14159/* Legal */314159E-5L/* Legal */510E/* Illegal: incomplete exponent */210f/* Illegal: no decimal or exponent */.e55 /* Illegal: missing integer or fraction */2.1.9 Character ConstantsCharacter literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variableof chartype.A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universalcharacter (e.g., '\u02C0').There are certain characters in C when they are preceded by a backslash they will have specialmeaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some ofsuch escape sequence codes:Escape Meaningsequence\\ \ character\' ' character\\" \" character\? ? character\a Alert or bell\b Backspace\f Form feed\n Newline\r Carriage return\t Horizontal tab\v Vertical tab\ooo Octal number of one to three digits\xhh . . . Hexadecimal number of one or more digitsFollowing is the example to show few escape sequence characters:#include<stdio.h> 2011 – mm/dd Page 9int main(){printf(\"Hello\tWorld\n\nroboVics\n\");SoftProduct Name of ClassTraining Manual

return0;}When the above code is compiled and executed, it produces the following result:Hello WorldroboVics2.1.10 String literalsString literals or constants are enclosed in double quotes \"\". A string contains characters that aresimilar to character literals: plain characters, escape sequences, and universal characters.You can break a long line into multiple lines using string literals and separating them usingwhitespaces.Here are some examples of string literals. All the three forms are identical strings. \"hello, dear\" \"hello, \ dear\" \"hello, \"\"d\"\"ear\" 2.1.11 Defining Constants There are two simple ways in C to define constants:1. Using #define preprocessor.2. Using const keyword. 2.1.12 The #define Preprocessor Following is the form to use #define preprocessor to define a constant:#define identifier valueFollowing example explains it in detail:#include<stdio.h>#define LENGTH 10#define WIDTH 5#define NEWLINE '\n'int main(){int area;area= LENGTH * WIDTH;printf(\"value of area : %d\", area);printf(\"%c\", NEWLINE);2011 – mm/dd SoftProduct Name of ClassPage 10 Training Manual

return 0;}When the above code is compiled and executed, it produces the following result:value of area : 502.1.13 The const KeywordYou can use const prefix to declare constants with a specific type as follows:const type variable = value;Following example explains it in detail:#include<stdio.h>int main(){const int LENGTH =10;const int WIDTH =5;const char NEWLINE ='\n';int area;area= LENGTH * WIDTH;printf(\"value of area : %d\", area);printf(\"%c\", NEWLINE);return 0;}When the above code is compiled and executed, it produces the following result:value of area : 50Note that it is a good programming practice to define constants in CAPITALS.2.2C - Operators2.2.1 Arithmetic OperatorsFollowing table shows all the arithmetic operators supported by C language. Assumevariable A holds 10 and variable B holds 20 then:Operator Description Example+ Adds two operands- Subtracts second operand from the first A + B will give 30SoftProduct Name of Class A - B will give -10Training Manual 2011 – mm/dd Page 11

* Multiplies both operands A * B will give 200/ Divides numerator by de-numerator B / A will give 2% Modulus Operator and remainder of after an integer division B % A will give 0++ Increments operator increases integer value by one A++ will give 11-- Decrements operator decreases integer value by one A-- will give 92.2.2 Relational OperatorsFollowing table shows all the relational operators supported by C language. Assume variable A holds10 and variable B holds 20, then:Operator Description Example== Checks if the values of two operands are equal or not, if yes then condition (A == B) becomes true. is not true.!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not< Checks if the value of left operand is less than the value of right operand, if yes true. then condition becomes true. (A < B)>= Checks if the value of left operand is greater than or equal to the value of right is true. operand, if yes then condition becomes true. (A >= B)<= Checks if the value of left operand is less than or equal to the value of right is not operand, if yes then condition becomes true. true. (A <= B) is true.2.2.3 Logical OperatorsFollowing table shows all the logical operators supported by C language. Assume variable A holds 1and variable B holds 0, then:Operator Description Example&& Called Logical AND operator. If both the operands are non-zero, then condition (A && B) becomes true. is false.|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is condition becomes true. true.! Called Logical NOT Operator. Use to reverses the logical state of its operand. If !(A && a condition is true then Logical NOT operator will make false. B) is true.2.2.4 Bitwise OperatorsBitwise operator works on bits and perform bit-by-bit operationThe Bitwise operators supported by C language are listed in the following table. Assume variable Aholds 60 and variable B holds 13, then:Operator Description Example2011 – mm/dd SoftProduct Name of ClassPage 12 Training Manual

& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12, which is 0000 1100| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49, which is 0011 0001 (~A ) will give -61,~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. which is 1100 0011 in 2's complement form.<< Binary Left Shift Operator. The left operands value is moved left by the number of A << 2 will give 240 bits specified by the right operand. which is 1111 0000>> Binary Right Shift Operator. The left operands value is moved right by the number A >> 2 will give 15 of bits specified by the right operand. which is 0000 11112.2.5 Assignment OperatorsThere are following assignment operators supported by C language:Operator Description Example=+= Simple assignment operator, Assigns values from right side operands to left side C = A + B will assign-=*= operand value of A + B into C/= Add AND assignment operator, It adds right operand to the left operand and C += A is equivalent to assign the result to left operand C=C+A Subtract AND assignment operator, It subtracts right operand from the left C -= A is equivalent to operand and assign the result to left operand C=C-A Multiply AND assignment operator, It multiplies right operand with the left operand C *= A is equivalent to and assign the result to left operand C=C*A Divide AND assignment operator, It divides left operand with the right operand C /= A is equivalent to and assign the result to left operand C=C/A%= Modulus AND assignment operator, It takes modulus using two operands and C %= A is equivalent assign the result to left operand to C = C % A<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2&= Bitwise AND assignment operator C &= 2 is same as C =SoftProduct Name of Class C&2Training Manual 2011 – mm/dd Page 13

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C =|= bitwise inclusive OR and assignment operator C^2 C |= 2 is same as C = C|22011 – mm/dd SoftProduct Name of ClassPage 14 Training Manual

3 Decision MakingDecision making structures require that the programmer specify one or more conditions to beevaluated or tested by the program, along with a statement or statements to be executed if thecondition is determined to be true, and optionally, other statements to be executed if the conditionis determined to be false.Following is the general form of a typical decision making structure found in most of theprogramming languages:C programming language assumes any non-zero and non-null values as true, and if it iseither zeroor null, then it is assumed as false value.Example if(0) = if (false) = if (null) = if ( 4-0+4). if (1) = if (true) = if (n) .3.1if...else statement An if statement can be followed by an optional else statement, which executes when theboolean expression is false.3.1.1 SyntaxThe syntax of an if...else statement in C programming language is: if(boolean_expression) 2011 – mm/dd{ Page 15/* statement(s) will execute if the boolean expression is true */}else{/* statement(s) will execute if the boolean expression is false */SoftProduct Name of ClassTraining Manual

}Example (1) #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_lcd.h\" #include \"C:\API\ev3_output.h\" #include \"C:\API\input.h\" #define Port0 0 #define SPEED 50 int main(){ robotMotionInit(); while(1){ int a =waitForColor(Port0); int b =waitForColor(Port0); if(a ==4){ break; } if( a == b ){ robotForward(SPEED); } else if( a != b ){ robot_stop(); } } robotMotionExit(); }2011 – mm/dd SoftProduct Name of ClassPage 16 Training Manual

Example (2)#include <stdio.h>#include \"C:\API\ev3_command.h\"#include \"C:\API\ev3_lcd.h\"#include \"C:\API\ev3_output.h\"#include \"C:\API\input.h\"int main(){inputInit();//initialize Input portssetModeIrRemote(0); //make IR sensor which is connected toPORT_1 in Remote Mode int x; int lSpeed=30, rSpeed=30;// L -> left motor speed , R -> Right motor speed robotMotionInit();//initialize Motorswhile(1){ x =getRemoteValue(0,0);// get IR remote input if(x ==4) break;// stop everything else robot_motors(lSpeed,rSpeed); if(x==1){// turn right lSpeed+=5; rSpeed-=5; } else if(x ==2){// turn left lSpeed-=5; rSpeed+=5; } } robotMotionExit();return 0;}3.2C - switch statement A switch statement allows a variable to be tested for equality against a list of values. Eachvalue is called a case, and the variable being switched on is checked for each switch case.3.2.1 SyntaxThe syntax for a switch statement in C programming language is as follows:switch(expression){ :case constant-expression :statement(s);break;/* optional */case constant-expressionstatement(s);break;/* optional *//* you can have any number of case statements */ 2011 – mm/dddefault:/* Optional */ Page 17statement(s);SoftProduct Name of ClassTraining Manual

}Example (3) #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_lcd.h\" #include \"C:\API\input.h\" #include \"C:\API\ev3_output.h\" int main() { LcdInit(); robotMotionInit(); int colorNumber; colorNumber=waitForColor(0); switch(colorNumber){ case(0): LcdText(1,10,10,\"You didn't detect color \"); break; case(3): LcdText(1,10,10,\"Green Color \"); robotForwardT(50,1000); break; case(5): LcdText(1,10,10,\"Red Color \"); robotBackwardT(50,1000); break; default: LcdText(1,10,10,\"Try again ... \"); wait(SEC_2); LcdClearDisplay(); } LcdExit(); robotMotionExit(); }2011 – mm/dd SoftProduct Name of ClassPage 18 Training Manual

3.3Conditional Operators (( ? : ) Operator )can be used to replace if...elsestatements. It has the following general form:Exp1?Exp2:Exp3;Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.which it is equivalent toif(Exp1){ Exp2 ; Exp3 ; }else{ }SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 19

4 Loops Loops cause program to execute the certain block of code repeatedly until test condition is false. Loops are used in performing repetitive task in programming. Consider these scenarios:• You want to execute some code/s 100 times.• You want to execute some code/s certain number of times depending upon input from user. These types of task can be solved in programming using loops. C programming language provides the following types of loop to handle looping requirements.Loop Type Descriptionwhile loopfor loop Repeats a statement or group of statements while a given condition isdo...while loop true. It tests the condition before executing the loop body.nested loops Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. Like a while statement, except that it tests the condition at the end of the loop body You can use one or more loop inside any another while, for or do..while loop.4.1Loop Control Statements:Loop control statements change execution from its normal sequence. When execution leaves ascope, all automatic objects that were created in that scope are destroyed.C supports the following control statements.Control Statement Descriptionbreak statementcontinue statement Terminates the loop or switch statement and transfers execution to thegoto statement statement immediately following the loop or switch. Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.2011 – mm/dd SoftProduct Name of ClassPage 20 Training Manual

4.2For loop For loops in C are straightforward. They supply the ability to create a loop - a code block that runs multiple times. For loops require an iterator variable, usually notated as i. For loops give the following functionality:• Initialize the iterator variable using an initial value• Check if the iterator has reached its final value• Increases the iterator 4.2.1 Syntax: The syntax of a for loop in C programming language is: for(init; condition; increment ) { statement(s); } 4.2.2 How for loop works in C programming? The initialization statement is executed only once at the beginning of the for loop. Then the test expression is checked by the program. If the test expression is false, for loop is termi- nated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false. This flowchart describes the working of for loop in C programmingSoftProduct Name of Class 2011 – mm/ddTraining Manual Page 21

For example, if we wish to iterate on a block for 10 times, we write: #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_lcd.h\" int main () { int i; for (i = 0; i < 10; i++) { writeInt(1,10,10,i); wait(SEC_1); } }This block will print the numbers 0 through 9 (10 numbers in total).For loops can iterate on array values. For example, if we would want to sum all the values of an ar-ray, we would use the iterator i as an the array index:2011 – mm/dd SoftProduct Name of ClassPage 22 Training Manual

Another Example :Program to move the robot for number of steps and after every step the robot wait for 1 second tomove the next step. #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_output.h\" #include \"C:\API\ev3_lcd.h\" int main() { robotMotionInit(); int stepsNumber; for(stepsNumber=0;stepsNumber<10;stepsNumber++) { robotForwardT(10,1000); wait(SEC_1); } robotMotionExit(); }4.3While loopThe while loop checks whether the test expression is true or not. If it is true, code/s insidethe body of while loop is executed,that is, code/s inside the braces { } are executed. Thenagain the test expression is checked whether test expression is true or not. This processcontinues until the test expression becomes false.4.3.1 Syntax:The syntax of a while loop in C programming language is:while(condition){statement(s);}SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 23

#include <stdio.h>#include \"C:\API\ev3_command.h\"#include \"C:\API\ev3_lcd.h\"int main (){int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };int sum = 0;int i;for (i = 0; i < 10; i++) {sum += array[i];}/* sum now contains a[0] + a[1] + ... + a[9] */LcdText(1,5,10,\"Sum of the array is\");writeInt(1,10,20,sum);}Here, statement(s) may be a single statement or a block of statements. The condition may be anyexpression, and true is any nonzero value. The loop iterates while the condition is true.When the condition becomes false, program control passes to the line immediately following theloop.This flowchart describes the working of while loop in C programmingFor example, the following code will execute exactly ten times:2011 – mm/dd SoftProduct Name of ClassPage 24 Training Manual

#include <stdio.h>int main(){int n = 0;while (n < 10) {n++;printf(\" %d \n\",n);}}While loops can also execute infinitely if a condition is given which always evaluates as true (non-zero):while (1) { /* do something */}For example, Program to make robot rotate for number of times. #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_output.h\" int main() { robotMotionInit(); int rotateNumber; while(rotateNumber>0) { robot_rotate(50); --rotateNumber; } robotMotionExit(); }4.4do ..while loopdo...while loop is very similar to while loop. Only difference between these two loops isthat, in while loops, test expression is checked at first but, in do...while loop code isexecuted at first then the condition is checked. So, the code are executed at least once indo...while loops.4.4.1 Syntax:The syntax of a do...while loop in C programming language is:do{statement(s);}while( condition );This flowchart describes the working of do ..while loop in C programmingSoftProduct Name of Class 2011 – mm/ddTraining Manual Page 25

For Example, Program to display number on LCD and if the number greater than 5 display thesenumbers on LCD#include <stdio.h>#include \"C:\API\ev3_command.h\"#include \"C:\API\ev3_lcd.h\"int main (){ LcdInit(); int Number =5; do{ writeInt(1,10,10,Number); -- Number ; } while(Number >5);LcdExit();}4.5Nested LoopC programming language allows to use one loop inside another loop.4.5.1 Syntax:The syntax for a nested for loop statement in C is as follows: SoftProduct Name of Class Training Manualfor(init; condition; increment ){for(init; condition; increment ){statement(s);}statement(s);}2011 – mm/ddPage 26

The syntax for a nested while loop statement in C programming language is as follows:while(condition){while(condition){statement(s);}statement(s);}The syntax for a nested do...while loop statement in C programming language is as follows:do{statement(s);do{statement(s);}while( condition );}while( condition );A final note on loop nesting is that you can put any type of loop inside of any other type of loop.4.6break Statementbreak is used in terminating the loop immediately after it is encountered. The breakstatement is used with conditional if statement.4.6.1 SyntaxThe syntax for a break statement in C is as follows:break;The break statement halts a loop after ten loops, even though the while loop never finishes:#include <stdio.h>int main (){int n = 0;while (1) {n++;printf(\" %d \n\",n);if (n == 10) {printf(\"End because n = %d \n\",n);break; }}} 2011 – mm/dd Page 27SoftProduct Name of ClassTraining Manual

4.7Continue StatementIt is sometimes desirable to skip some statements inside the loop. In such cases, continuestatements are used.4.7.1 Syntax:The syntax for a continue statement in C is as follows:continue;In the following code, the continue directive causes the printf command to be skipped, so that onlyeven numbers are printed out:4.8#include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_lcd.h\"4.9int main () { int n = 0;4.10while (n < 10) { n++; /* check that n is odd */4.11if (n % 2 == 1) { /* go back to the start of the while block */ continue;4.12} /* we reach this code only if n is even */4.13LcdText(1,10,10,\"The number\"); writeInt(1,10,20,n); LcdText(1,10,30,\"is even \");4}}.144.15 goto Statementgoto statement is used for altering the normal sequence of program execution bytransferring control to some other part of the program.4.15.1 Syntax:The syntax for a goto statement in C is as follows:goto label;...label: statement;2011 – mm/dd SoftProduct Name of ClassPage 28 Training Manual

5 Functions In programming, a function is a segment that groups code to perform a specific task. A C program has at least one function main( ). Without main() function, there is technically no C program. 5.1Types of C functions Basically, there are two types of functions in C on basis of whether it is defined by user or not.• Library function• User defined function 5.1.1 Library function Library functions are the in-built function in C programming system. For example: Main ( ) The execution of every C program starts from this main() function. 5.1.2 User defined function C allows programmer to define their own function according to their requirement. These types of functions are known as user-defined functions. Suppose, a programmer wants to find factorial of a number and check whether it is prime or not in same program. Then, he/she can create two separate user-defined functions in that program: one for finding fac- torial and other for checking whether it is prime or not. 5.1.2.1 How user-defined function works in C Programming? #include <stdio.h> void function_name (){ ………………… } int main (){ …………………… Function_name (); …………………… }Every C program begins from main() and program starts executing the codesinside main() function. When the control of program reachesto function_name() inside main()function. The control of program jumps to voidfunction_name() and executes the codes inside it. When all the codes inside that user-definedSoftProduct Name of Class 2011 – mm/ddTraining Manual Page 29

function are executed, control of the program jumps to the statement justafter function_name() from where it is called.Example of user-defined functionC program to add two integers. Make a function add to add integers and display sum inmain() function. #include <stdio.h> int add (int a ,int b); int main() { int firstNumber,secondNumber,sum ; printf(\"Enters two number to add\n\"); scanf (\"%d %d\",&firstNumber,&secondNumber); sum = add(firstNumber , secondNumber); printf(\"sum=%d \n\",sum); } int add (int a , int b) { return (a+b); }5.2Function prototype(declaration):Every function in C programming should be declared before they are used. These type ofdeclaration are also called function prototype. Function prototype gives compiler infor-mation about function name, type of arguments to be passed and return type.5.2.1 Syntax of function prototypereturn_type function_name (type(1) argument(1),…………… ,type(n)argument(n)) In the above example,int add(int a, int b); is a function prototype which provides following in- formation to the compiler:1. name of the function is add()2. return type of the function is int.3. two arguments of type int are passed to function. Function prototype are not needed if user-definition function is written be- fore main() function. 5.3Function call Control of the program cannot be transferred to user-defined function unless it is called invoked.2011 – mm/dd SoftProduct Name of ClassPage 30 Training Manual

5.3.1 Syntax of function callfunction_name (argument(1),…………… ,argument(n))In the above example, function call is made using statement add(num1,num2); from main(). This make the control of program jump from that statement to function definition and executes the codes inside that function.5.4Function definitionFunction definition contains programming codes to perform specific task.5.4.1 Syntax of function definitionreturn_type function_name (type(1) argument(1),…………… ,type(n)argument(n)){ //body of function}Function definition has two major components:5.4.2 Function declaratorFunction declarator is the first line of function definition. When a function is called, controlof the program is transferred to function declarator.5.4.2.1 Syntax of function declaratorreturn_type function_name (type(1) argument(1),…………… ,type(n)argument(n))Syntax of function declaration and declarator are almost same except, there is no semicolon atthe end of declarator and function declarator is followed by function body.In above example, int add(int a,int b) is a function declarator.5.4.3 Function bodyFunction declarator is followed by body of function inside braces.5.5Passing arguments to functionsIn programming, argument(parameter) refers to data this is passed to function(functiondefinition) while calling function.In above example two variable, num1 and num2 are passed to function during function calland these arguments are accepted by arguments a and b in function definition.SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 31

Arguments that are passed in function call and arguments that are accepted in function definition should have same data type. For example: If argument num1 was of int type and num2 was of float type then, argument varia- ble a should be of type int and b should be of type float,i.e., type of argument during func- tion call and function definition should be same. A function can be called with or without an argument. 5.6Return Statement Return statement is used for returning a value from function definition to calling function. 5.6.1 Syntax of return statement return (expression); In above example, value of variable add in add() function is returned and that value is stored in variable sum in main() function. The data type of expression in return statement should also match the return type of function. 5.7Types of User-defined Functions in C Programming For better understanding of arguments and return type in functions, user-defined functions can be categorised as:1. Function with no arguments and no return value2. Function with no arguments and return value3. Function with arguments but no return value4. Function with arguments and return value.5.8RecursionA function that calls itself is known as recursive function and this technique is known asrecursion in C programming.Example of recursion in C programmingprogram to Calculate Factorial of a Number Using Recursion2011 – mm/dd SoftProduct Name of ClassPage 32 Training Manual

#include<stdio.h>long factorial(int n);int main(){ int n; printf(\"Enter an positive integer: \"); scanf(\"%d\",&n); printf(\"Factorial of %d = %ld\", n, factorial(n)); return 0;}long factorial(int n){ if(n==1) return 1; return n*factorial(n-1);}This program takes a positive integer from user and calculates the factorial of that number.Instead of loops to calculate factorial, this program uses recursive function to calculate thefactorial of a number.Recursion is more elegant and requires few variables which make program clean. Recursion can beused to replace complex nesting code by dividing the problem into same problem of its sub-type.Example 1Program to make the robot dance #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_output.h\" void yoyo(char speed, unsigned long waitTime) { robotForward(speed); Wait(waitTime); robotBackward(speed); Wait(waitTime); robot_stop(); } void wiggle(char speed, unsigned long waitTime) { robot_rotate(-speed); Wait(waitTime); robot_rotate(speed); Wait(waitTime); robot_stop(); } void dance() { yoyo(63,500); yoyo(63,500); wiggle(63,1000); wiggle(63, 1000); } int main (); { dance(); }SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 33

Example 2Program to use the robot to make circle #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_output.h\" void circle (); int main () { robotMotionInit(); circle (); robotMotionExit(); } void circle () { robot_motors (50,100); }2011 – mm/dd SoftProduct Name of ClassPage 34 Training Manual

6 Array and StringArrays are special variables which can hold more than one value using the same variable, using anindex. an array is a sequence of data item of homogeneous value(same type)6.1Declaring ArraysTo declare an array in C, a programmer specifies the type of the elements and the number ofelements required by an array as follows:type arrayName [ arraySize ];6.1.1 Array elementsSize of array defines the number of elements in an array. Each element of array can be ac-cessed and used by user according to the need of program. For example:int age [5] ;Note that, the first element is numbered 0 and so on.Here, the size of array age is 5 times the size of int because there are 5 elements.Suppose, the starting address of age[0] is 2120d and the size of int be 4 bytes. Then, thenext address (address of a[1]) will be 2124d, address of a[2] will be 2128d and so on.6.1.2 Initializing ArraysYou can initialize array in C either one by one or using a single statement as follows:double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};The number of values between braces { } can not be larger than the number of elements that wedeclare for the array between square brackets [ ].If you omit the size of the array, an array just big enough to hold the initialization is created.Therefore, if you write:double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};6.1.3 Accessing Array ElementsAccessing a number from the array is done using the same syntax. Notice that arrays in C are zero-based, which means that if we defined an array of size 10, then the array cells 0 through 9 (inclu-sive) are defined. numbers[10] is not an actual value.SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 35

int numbers[10];/* populate the array */numbers[0] = 10;numbers[1] = 20;numbers[2] = 30;numbers[3] = 40;numbers[4] = 50;numbers[5] = 60;numbers[6] = 70;Arrays can only have one type of variable, because they are implemented as a sequence of values inthe computer's memory. Because of that, accessing a random array cell is very efficient.This example take input from IR remote this value is from 1->4 then access speed array elementwith this input get the speed value in it but because c is zero based we subtract 1 from the inputvalue. #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_lcd.h\" #include \"C:\API\input.h\" #include \"C:\API\ev3_output.h\" int main() { LcdInit(); robotMotionInit(); char speed [4] = {30,60,90,120} ; int index ; LcdText(1,10,10,\"Enter speed value \") ; wait(SEC_2); LcdClearDisplay() ; index = getRemoteValue(0,0) - 1 ; writeInt(1,10,10,index); robot_translate(speed[index]); wait(SEC_4); robot_stop(); LcdExit(); robotMotionExit(); }6.2Arrays and FunctionsA single array element or an entire array can be passed to a function. Also, arrays can bepassed to function as argument.2011 – mm/dd SoftProduct Name of ClassPage 36 Training Manual

6.2.1 Passing Array In FunctionSingle element of an array can be passed in similar manner as passing variable to a functionExampleA Program to pass a single element of an array of speed to function to move the robot forward orbackward #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_output.h\" void move (char a); int main () { robotMotionInit(); char speed[]={-100,-50,-10,10,50,100}; move (speed[2]); wait(SEC_2); robot_stop(); robotMotionExit(); } void move (char a) { robot_translate(a); }6.2.2 Passing entire array to a functionWhile passing arrays to the argument, the name of the array is passed as an argument (,i.e, startingaddress of memory area is passed as argument).ExampleProgram to pass an array containing numbers of speed to a function. This function should findaverage number and return the average to function to move the robot.SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 37

#include <stdio.h>#include \"C:\API\ev3_command.h\"#include \"C:\API\ev3_output.h\"char average (char a[]);int main (){ robotMotionInit(); char speed[]={23,123,36,87,10,50,100}; char avg=average(speed); robot_translate(avg); wait(SEC_2); robot_stop(); robotMotionExit();}char average (char a[]){ int i; char avg,sum = 0; for(i=0;i<7;i++) { sum+=a[i]; } avg = (sum/7); return avg;} 6.3Multidimensional Arrays C programming language allows programmer to create arrays of arrays known as multidimensional arrays. For example: Float a[2][6]; Here, a is an array of two dimension, which is an example of multidimensional array. This array has 2 rows and 6 columns For better understanding of multidimensional arrays, array elements of above example can be thinked of as below:6.3.1 Initialization of Multidimensional ArraysMultidimensional arrays can be initialized in different number of ways.int c[2][3]={{1,3,0}, {-1,5,9}}; SoftProduct Name of Class OR Training Manualint c[][3]={{1,3,0}, {-1,5,9}};2011 – mm/ddPage 38

ORint c[2][3]={1,3,0,-1,5,9};Example of Multidimensional Array #include <stdio.h> int main () { /* an array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j; for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf(\"a[%d][%d] = %d\n\", i,j, a[i][j] ); } } return 0; }6.4String6.4.1 Defining stringsStrings in C are actually arrays of characters. Although pointers in C is in advanced subject explainedlater on, we will use pointers to a character array to define simple strings, in the following manner:char * name = \"John Smith\";This method creates a string which we can only use for reading. If we wish to define a string whichcan be manipulated, we will need to define it as a local character array:char name[] = \"John Smith\";This notation is different because it allocates an array variable so we can manipulate it. The emptybrackets notation [] tells the compiler to calculate the size of the array automatically. This is in factthe same as allocating it explicitly, adding one to the length of the string:char name[] = \"John Smith\";/* is the same as */char name[11] = \"John Smith\";The reason that we need to add one, although the string John Smith is exactly 10 characters long, isfor the string termination, a special character (equal to 0) which indicates the end of the string. Theend of the string is marked because the program does not know the length of the string - only thecompiler knows it according to the code.SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 39

6.4.2 Passing Strings to FunctionsString can be passed to function in similar manner as arrays as, string is also an array. #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_lcd.h\" void display (char *str); int main() { LcdInit(); char name[]=\"roboVICS\"; display(name); LcdExit(); } void display (char *str ) { LcdText(1,10,10,str) ; wait(SEC_1); }6.4.3 String Manipulations In C Programming Using Library FunctionsStrings are often needed to be manipulated by programmer according to the need of aproblem. All string manipulation can be done manually by the programmer but, this makesprogramming complex and large. To solve this, the C supports a large number of stringhandling functions.There are numerous functions defined in \"string.h\" header file.S.N. Function & Purpose1 strcpy(s1, s2); Copies string s2 into string s1.2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.3 strlen(s1); Returns the length of string s1.4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.Strings handling functions are defined under \"string.h\" header file, i.e, you have to includethe code below to run string handling functions.#include <string.hFollowing example makes use of few of the above-mentioned functions:2011 – mm/dd SoftProduct Name of ClassPage 40 Training Manual

#include <stdio.h>#include <string.h>#include \"C:\API\ev3_command.h\"#include \"C:\API\ev3_lcd.h\"void display (char ch[]);int main (){ LcdInit(); char str1[] = \"Hello\"; char str2[] = \"World\"; char str3[]; int len ; strcpy(str3, str1); display(str3); strcat( str1, str2); display(str1); len = strlen(str1); writeInt(1,10,10,len); LcdExit();}void display (char []){ LcdText(1,10,10,char) ; wait(SEC_1); LcdClearDisplay() ;}SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 41

7 PointersPointers are the powerful feature of C , which differs it from other popular programming languageslike: java and Visual Basic.Pointers are used in C program to access the memory and manipulate the address.7.1Reference operator (&)If var is a variable then, &var is the address in memory.int var=5;printf(“Value : %d\n”,var);printf(“Address : %d\n”,&var);output :value = 5Address = 26867787.2What Are Pointers?A pointer is a variable whose value is the address of another variable, i.e., direct address of thememory location. Like any variable or constant, you must declare a pointer before you can use it tostore any variable address. The general form of a pointer variable declaration is:type *var-name;Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of thepointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use formultiplication. However, in this statement the asterisk is being used to designate a variable as apointer. Following are the valid pointer declaration:int *ip; /* pointer to an integer */double *dp; /* pointer to a double */float *fp; /* pointer to a float */char *ch /* pointer to a character */The actual data type of the value of all pointers, whether integer, float, character, or otherwise, isthe same, a long hexadecimal number that represents a memory address. The only difference be-tween pointers of different data types is the data type of the variable or constant that the pointerpoints to.Example To Demonstrate Working of Pointers2011 – mm/dd SoftProduct Name of ClassPage 42 Training Manual

#include <stdio.h> int main(){ int *pc,c; c=22; printf(\"Address of c:%d\n\",&c); printf(\"Value of c:%d\n\n\",c); pc=&c; printf(\"Address of pointer pc:%d\n\",pc); printf(\"Content of pointer pc:%d\n\n\",*pc); c=11; printf(\"Address of pointer pc:%d\n\",pc); printf(\"Content of pointer pc:%d\n\n\",*pc); *pc=2; printf(\"Address of c:%d\n\",&c); printf(\"Value of c:%d\n\n\",c); return 0; }OutputAddress of c: 2686784Value of c: 22Address of pointer pc: 2686784Content of pointer pc: 22Address of pointer pc: 2686784Content of pointer pc: 11Address of c: 2686784Value of c: 2 Explanation of program and figure1. Code int *pc, p; creates a pointer pc and a variable c. Pointer pc points to some address and that address has garbage value. Similarly, variable c also has garbage value at this point.2. Code c=22; makes the value of c equal to 22, i.e.,22 is stored in the memory location of variable c.3. Code pc=&c; makes pointer, point to address of c. Note that, &c is the address of variable c (because c is normal variable) and pc is the address of pc (because pc is the pointer varia- ble). Since the address of pc and address of c is same, *pc (value of pointer pc) will be equal to the value of c.4. Code c=11; makes the value of c, 11. Since, pointer pc is pointing to address of c. Value of *pc will also be 11.5. Code *pc=2; change the contents of the memory location pointed by pointer pc to change to 2. Since address of pointer pc is same as address of c, value of c also changes to 2.SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 43

7.3Pointer arithmetic7.3.1 Incrementing a PointerWe prefer using a pointer in our program instead of an array because the variable pointer can beincremented, unlike the array name which cannot be incremented because it is a constant pointer.The following program increments the variable pointer to access each succeeding element of thearray: #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; ptr = var; for ( i = 0; i < MAX; i++) { printf(\"Address of var[%d] = %x\n\", i, ptr ); printf(\"Value of var[%d] = %d\n\", i, *ptr ); /* move to the next location */ ptr++; } return 0; }When the above code is compiled and executed, it produces result something as follows:Address of var[0] = bf882b30Value of var[0] = 10Address of var[1] = bf882b34Value of var[1] = 100Address of var[2] = bf882b38Value of var[2] = 2007.4Pointers and ArraysArrays are closely related to pointers in C programming but the important differencebetween them is that, a pointer variable can take different addresses as value whereas, incase of array it is fixed. This can be demonstrated by an example:#include <stdio.h>int main(){ char c[4]; int i;Addrfesosr(oif=c0[;0i]<=248;f+f+4i4 ){Address porficn[t1f](=2\"8Afdfd4r5ess of c[%d]=%x\n\",i,&c[i]);Addr}ess of c[2]=28ff46Addrresestuorfnc[03;]=28ff47}Notice, that there is equal difference (difference of 1 byte) between any two consecutiveelements of array.2011 – mm/dd SoftProduct Name of ClassPage 44 Training Manual


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook