Unit 2

1. Introduction of C:
C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use. C has been around for several decades and has won widespread acceptance because it gives programmers maximum control and efficiency. C is an easy language to learn.

On compiling

C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute). The C program is the humanreadable form, while the executable that comes out of the compiler is the

machine-readable and executable form. What this means is that to write and run a C program, you must have access to a C compiler. You can use Turbo C or Turbo C++ Compilers for this purpose.

2. History of C
The milestones in C's development as a language are listed below:
• •

UNIX developed c. 1969 -- DEC PDP-7 Assembly Language BCPL -- a user friendly OS providing powerful development tools developed from BCPL. Assembler tedious long and error prone. A new language ``B'' a second attempt. c. 1970. A totally new language ``C'' a successor to ``B''. c. 1971 By 1973 UNIX OS almost totally written in ``C''.

• • •

3. Features of C
• • • • • •

Small size Extensive use of function calls Loose typing -- unlike PASCAL Structured language Low level (Bitwise) programming readily available Pointer implementation - extensive use of pointers for memory, array, structures and functions.

C has now become a widely used professional language for various reasons.
• •

It has high-level constructs. It is robust language whose rich set of built-in functions and operators can be used to write any complex program. It can handle low-level activities. It produces efficient programs.

• •

• • •

It is fast. (much faster than BASIC). It can be compiled on a variety of computers. It has the ability to extend itself(A C program is basically collection of functions that are supported by the C Library, We can continuously add our own functions to the C Library)

4. C Program Structure
A C program basically has the following form: Documentation Section Link Section Definition Section Global Declaration Section Main() Function Section { Declaration Part Executable Part

} Subprogram Section Function 1 Function 2 ….. …….. Function n

main() Function Section: Every program must have one main () function section It contains declaration part and executable part. the author and other details which the programmer would like to use later.h> int main() { printf("This is output from my first program!\n"). Global Section: Here those variables are declared which are used in more than one function. Link Section: This section provides instruction to the complier to link functions from the system library. 6. 3. 2. Definition section: This section defines all symbolic constants. Documentation Section: This section consists of a set of comments lines giving the name of the program. Subprogram Section: It contains all the user-defined functions that are called in the main function.1. The Simplest C Program: What's Happening? #include <stdio. return 0. 4. . 5.

time and math libraries. write output to the screen (called "standard out"). or if it calculates a value. The line int main() declares the main function. The way your program remembers things is by using variables." symbols for carriage returns (\n). For example: . • In C. The portion in quotes is called the format string and describes how the data is to be formatted when printed.. • The printf statement in C allows you to send output to standard out (for us. The standard I/O library lets you read input from the keyboard (called "standard in"). At run time. 5. The format string can contain string literals such as "This is output from my first program!. C has a large number of standard libraries like stdio. you will want to remember it somewhere so you can use it later. Variables As a programmer.h>. This line includes the "standard I/O library" into your program. In this case. It is an extremely useful library. you will frequently want your program to "remember" a value. if your program requests a value from the user. the { and } symbols mark the beginning and end of a block of code. and operators as placeholders for variables. Every C program must have a function named main somewhere in the code. process text files stored on the disk.} This C program starts with #include <stdio. the block of code making up the main function contains two lines. the screen). For example. including string. program execution starts at the first line of the main function. line causes the function to return an error code of 0 (no error) to the shell that started execution. and so on. • The return 0.

single character values (such as "m" or "Z") 6. "I want to create a space called b that is able to hold one integer value.integer (whole number) values float . User-defined data types 3. Derived data types 4. b) and a type (in this case. an integer). You can use the value in b by saying something like: printf ("%d". int. there are several standard types for variables: • • • int . This line says. Empty data set Primary Data type: .floating point values char . In C. You can store a value in b by saying something like: b = 5. Data Types: 1. Primary data types 2. b)." A variable has a name (in this case.int b.

These are userdefined names and consist of a sequence of letters and digits. 7.Other data types will discussed later………. All keywords must be written in lowercase. . with a letter as a first character. Both uppercase and lowercase letters are permitted. All keywords have fixed meanings and these meaning can’t be changed. Keywords serve as basic building blocks for program statements.. The underscore character is also permitted. Keywords and Identifiers Every C word is classified as either a keyword or an identifier. functions and arrays. ANSI C Keywords: auto break enum return unsigned default if break else register union continue goto static double long typedef const for size of while int switch char float signed volatile struct case extern short void do Identifiers refers to the names of variables.

8. Constants:
ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed. The const keyword is to declare a constant, as shown below: int const a = 1; const int a =2; Note:
• •

You can declare the const before or after the type. Choose one and stick to it. It is usual to initialize a const with a value as it cannot get a value any other way.

The preprocessor #define is another more flexible method to define constants in a program. You frequently see const declaration in function parameters. This says simply that the function is not going to change the value of the parameter. Basic types of constants:

Constants

Numeric Constants

Character Constants

Integer Constant s

Real Constant s

Single char Constants

String Constant s

Integer Constants: An integer constant refers to a sequence of digits. These are of three types a. Decimal b. Octal c. Hexadecimal Real Constants: These quantities are represented by numbers containing fractional parts like 17.548. Such numbers are called real constants.

Single Char Constants: These contains a single character enclosed within a pair of single quote marks. Example: ‘5’ ‘X’ String Constants: A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, special characters and blank space. Examples: “Hello!” “1987” “WELL DONE” Backslash Character Constants C supports some special backslash character constants that are used in output functions. For example, the symbol ‘\n’ stands for new line character. Although they contain two character but they represent a single character. Backslash Character Constants Constants ‘\a’ ‘\b’ ‘\f’ ‘\n’ ‘\r’ ‘\v’ ‘\’’ ‘\”’ ‘\?’ ‘\\’ Meaning Alert Backspace Form feed New line Carriage return Vertical tab Single quote Double quote Question mark Backslash

9. OPERATORS AND EXPRESSION

the expression is called Integer expression..0 / 7. Arithmetic Operators: Operator + * / % Meaning Addition or unary plus Subtraction or unary minus Multiplication Division Modulo Division Note: C does not have an operator for exponentiation Integer arithmetic: When both the operands in a single arithmetic expression are integers. Examples Let a = 14. The result is an approximation of correct value. b = 4 a – b = 10 a + b = 18 a * b = 56 a / b = 3 (decimal part truncated) a % b = 2 (remainder of division) Real arithmetic: An arithmetic operation involving only real operands is called real arithmetic. Integer arithmetic always yields an integer value. and the operation is called integer arithmetic..0 = 0. Examples: 6.857143 .a.

666667 Mixed Mode Arithmetic When one of the operands is real and the other is integer. If either operand is of the real type. postfix is increment afterwards. Prefix means. then only real operation is performed and result is always a real number. and ==.0 = 1. • C allows *= += /= -= operators.0 / 3. ++ specifies increment.specifies decrement. You can place these in front or on the back of variables. The two arithmetic operators that are used frequently are ++ and --. the expression is called a mixed – mode arithmetic expression. • There are six possibilities in C: <. Example 15 / 10. >=. These are important considerations when using these operators. <=. The same principles apply in C when you are comparing two objects. >. it is prefix if it is placed behind. increment before any operations are performed. Here we can point out the difference between syntax and semantics. but they have two completely different • . !=.5 15 / 10 = 1 • There are other operators available. Relational Operators: You probably are familiar with < and the > relational operators from mathematics.0. a = b is different from a == b.0 = . the -. If the operator is placed in front. The first four a self-explanatory.-2. it is postfix. the != stands for "not equals to" and == is "equivalent to". For example: a=a+1 a=a-1 a=a%b equivalent to equivalent to equivalent to a+=1 a-=1 a%=b b. Most C compilers will allow both statements to be used in conditionals like if.

Logical Operators: • • Logical operators simulate boolean algebra in C. ||. Make sure your assignment operators are where you want them to be and your relational where you want relational comparisons! c. This can be a good thing or a bad thing depending on the context. Conditional Operators: A ternary operator pair “?:” is available in C to construct conditional expressions of the form exp1 ? exp2 : exp3 Working: The exp1 is evaluated first. Take the above example into consideration. if it is nonzero (true) then the exp2 is evaluated and becomes the value of the expression. |. && is used to compare two objects with AND: x != 0 && y != 0 Expressions involving logical operators undergo Short-Circuit • Evaluation. d.meanings. &. exp3 is evaluated and its value becomes the value of the expression. A sampling of Logical/Boolean Operators: &&. If x! = 0 evaluates to false. If exp1 is false. the whole statement is false regardless of the outcome of y! = 0. Example: . and ^. Operator && || ! Meaning logical AND logical OR logical NOT • For example.

a = 10. x = (a>b)?a:b. b = 15. Precedence and Associativity It is necessary to be careful of the meaning of such expressions as a + b * c . else b = b. or shifting them right or left. is equivalent to if (a > b) x = a. e. Bitwise Operators These operators are used for testing the bits. Operator & | << >> ~ ^ Meaning Bitwise AND Bitwise OR Shift left Shift right 1’s complement Bitwise exclusive OR 10. Bitwise operators may not be applied to float or double.

From high priority to low priority the order for all C operators is: Operators Associativity ( [ . Left to right ! . +. and high priority operators are evaluated before lower priority ones.++ -{. so that a-b-c is evaluated as (a-b)-c as you would expect. . Operators of the same priority are evaluated from left to right..We may want the effect as either (a + b) * c or a + (b * c) All operators have a priority.+ * & (type-cast) sizeof Right to left (in the above line.and * are the unary forms) * / % Left to right + Left to right << >> Left to right < <= > >= Left to right == != Left to right & Left to right ^ Left to right | Left to right && Left to right || Left to right ?: Left to right = += -= *= /= %= &= ^= |= <<= >>= Right to left . Left to right Thus a < 10 && 2 * b < c .

long int to int causes dropping of the excess higher order bits Casting a Value: There are instances when we want to force a type conversion in a way that is different from automatic conversion. double to float caused rounding of digits. This problem can be solved by converting locally one of the variables to the floating as shown below: ratio = (float) female_number/male_number . the decimal part of the result of division would be lost and ratio would represent a wrong figure. types is automatically converted to the ‘higher’ type before the operation proceeds. float to int cause truncation of the fractional part. the ‘lower. If the operands are of different types. The final result of an expression is converted to the type of the variable on the left of the assignment sign before assigning the value to it. 3.is interpreted as ( a < 10 ) && ( ( 2 * b ) < c ) 12. However. 2. Example ratio = female_number/male_number Since female_number and male_number are declared as integers in the program. but during evaluation it adhere to very strict rules of type conversion. Type Conversions in Expressions: C permits mixing of constants and variables of different types in an expression. The result is higher type. 1. the following changes are introduced during final assignment.

name = getchar(). Reading a Character:  getchar() syntax is: variable_name=getchar(). The general form of cast is: (type-name) expression 13.The process of such a local conversion is known as casting a value. will assign the character ‘H’ to the variable name when we press the key H on the keyboard.  getche() getche() reads a character from standard input device but the character is not displayed on the screen and also carriage return is not accepted.  getch() getch() is also used to read a character from input device. Example char name. . getch() displays the character without accepting the carriage return. Basic I/O Functions 1.

syntax putchar(variable_name). Where variable_name is type char variable containing a character. arg list . Formatted input/output Function: printf() The function is defined as follows: int printf(char *format.these are copied to output. conversion specifications -. Returns number of characters printed. putchar(answer). 14.. The format string has 2 types of object: • • ordinary characters -. This statement displays character contained in the variable-name at the terminal.. Example: answer=’Y’. Writing a Character This function writes a character to the standard output device.) -prints to stdout the list of arguments according specified format string.denoted by % and listed in Table . Will display the character ‘Y’ on the screen.2.

X u s Type char int int int int char * Result single character decimal number octal number hexadecimal number lower/uppercase notation unsigned int print string terminated by f e.23e002 e or f whichever is most compact print % character 0 Between % and format char we can put: .(minus sign) -.m = field width. d = precision of number of digits after decimal point or number of chars from a string. " " Scientific Format -1.E g.17. . So: printf("%-2. integer number m.. -.ddd.Table: Printf/scanf format characters Format Spec (%) c i.d o x..left justify.d -.G % double/float format -m.3f\n".23478).field width.

The • • • . } Here is an explanation of the different lines in this program: • The line int a. b. c. c.5%%\n"). . The next line initializes the variable named a to the value 5. b. The computer adds the value in a (5) to the value in b (7) to form the result 12. a = 5. b. The next line sets b to 7. The next line adds a and b and "assigns" the result to c. b and c... return 0.outputs: VAT=17. declares three integer variables named a. printf("%d + %d = %d\n".h> int main() { int a. c). Integer variables hold whole numbers. and then places that new value (12) into the variable c. b = 7.5% Example: #include <stdio.235 and: printf("VAT=17. a.The output on the screen is: 17. c = a + b.

Scanf() This function is defined as follows: int scanf(char *format.reads from stdin and puts input in address of variables specified in args list.string). The +. args." • The printf statement then prints the line "5 + 7 = 12.&i). It matches the second %d with b and substitutes 7. scanf(``%s''.variable c is assigned the value 12. scanf(``%d''. The simplest application of scanf looks like this: .. For this reason. Returns number of chars read. the = in this line is called "the assignment operator. C matches up the first %d with a and substitutes 5 there. It matches the third %d with c and substitutes 12. b and c.. char string[80]." The %d placeholders in the printf statement act as placeholders for values. Then it prints the completed line to the screen: 5 + 7 = 12. We can just give the name of an array or string to scanf since this corresponds to the start address of the array/string. the = and the spacing are a part of the format line and get embedded automatically between the %d operators as specified by the programmer. Format control string similar to printf Note: The ADDRESS of variable or a pointer to one is required by scanf. There are three %d placeholders. and at the end of the printf line there are the three variable names: a.) -..

h stdio. The program will read in an integer value that the user enters on the keyboard (%d is for integers. cos . It is easy to forget the & sign. 15. Library Functions: C provides a rich set of built-in functions called as library functions. If we want to use mathematical functions like sin. These are already created functions.h Similarly we can include other library functions as required: string. It helps in making programming easy.h math.h conio.h . etc we need to include math. as is printf. and when you forget it your program will almost always crash when you run it.h time.scanf("%d".h graphics. so b must be declared as an int) and place that value into b. The scanf function uses the same placeholders as printf: You MUST put & in front of the variable used in scanf. &b).

if statements .Unit 3 1.

It has three basic forms: a). Nested if. if(test condition1) { if(test condition2) { statement-1 } else { statement-2 } } else { statement-3 } statement x d) The else if ladder . The if else statement if (test expression) { statement1 } else { statement2 } c).The if statement has the same function as other languages. Simple if if (test expression) { statement } b). else statements:..

.. For example:. ....int x.. . } else { z=y.y....if (condition 1 ) statement1 else if (expression) statement2 else if statement3………. } } Examples: ...... main() { if (x>0) { z=w.w.

2. If exp1 is false. is equivalent to . if it is nonzero (true) then the exp2 is evaluated and becomes the value of the expression. b = 15. exp3 is evaluated and its value becomes the value of the expression. Example: a = 10. x = (a>b)?a:b. The ?: operator A ternary operator pair “?:” is available in C to construct conditional expressions of the form exp1 ? exp2 : exp3 Working: The exp1 is evaluated first.

Switch Statement The C switch is similar to Pascal's case statement and it allows multiple choice of a selection of items at one level of a conditional where it is a far neater way of writing multiple if statements: switch (expression) { case item1: statement1. Another important use of goto is to exit from deeply nested loops when an error occurs. In case any goto statement is absolutely necessary. 3. it is useful to provide branching within a loop. But it is good practice to avoid goto statements. break. When goto is used. morever the logic becomes more complicated.if (a > b) x = a. case itemn: . else b = b. goto statement goto statement can transfer the control to any place in a program. 4. many computers generate less efficient code. break. it must be documented. case item2: statement2.

We can also have null statements by just including a . . The break is needed if you want to terminate the switch after execution of one choice. case ` ': numberofspaces++. break.g. break. The default case is optional and catches any other cases. variables are not allowed. break. or let the switch statement fall through by omitting any statements (see e. default: statement.statementn. } In each case the value of itemi must be a constant. For example:switch (letter) { case `A': case `E': case `I': case `O': case `U': numberofvowels++. below). Otherwise the next case would get evaluated. Note: This is unlike most other languages.

break. expression3 is the modifier (which may be more than just simple increment). If none of these is true then the default condition is executed. for loop The C for statement has the following form: for (expression1.break. default: numberofconstants++. 5.x-) . `I'.x>0. If the value of letter is ` ' then numberofspaces is incremented. that is numberofconstants is incremented. `O' or `U' then numberofvowels is incremented. 2. or {block of statements} expression1 initialises. NOTE: C basically treats for statements as while type loops For example: int x. `E'. expression2 is the terminate test. } In the above example if the value of letter is `A'. main() { for (x=3. expression3) statement.

y=4.((x>3) && (x<9)).. while loop The while statement is similar to those used in other languages although more can be done with the expression statement -.. z/=10) The second example shows that multiple expressions can be separated a .y=4.((x>3) && (y<9)). we are just trying to illustrate peculiar features of C for that may be useful:for (x=0. x++) for (x=0.y+=2) for (x=0. The practical application of such statements is not important here.a standard feature of C. The while has the form: while (expression) statement ..{ printf("x=%d\n". } } .. 6. In the third example the loop will continue to iterate until z becomes 0.z=4000.z.to the screen All the following are legal for statements in C..outputs: x=3 x=2 x=1 .x). x++.

to the screen. not just conditions. or x+=5.. the following are all legal:while (x--). Using this type of expression. .For example: int x=3. x--. while (x=x+1). main() { while (x>0) { printf("x=%d\n"..x). evaluates to 0 will the while condition fail and the loop be exited.outputs: x=3 x=2 x=1 . x=x+1. while (x+=5).. only when the result of x--. } } . Because the while loop can accept expressions..

writes a given char to screen. while (expression). 7. while ( (ch = getchar()) != `q') putchar(ch). The first example counts i up to 10.and putchar() .reads a character from the keyboard . } .x--). NOTE: This type of operation is used a lot in C and not just with character reading!! . For example: int x=3. The while loop will proceed to read from the keyboard and echo characters to the screen until a 'q' character is read. The second example uses C standard library functions getchar() . main() { do { printf("x=%d\n". do-while loop C's do-while statement has the form: do statement.We can go further still and perform complete operations within the while expression: while (i++ < 10). } while (x>0).

} This causes the two lines within the braces to be executed repeatedly until a is greater than or equal to b. } while (a < b).operator which uses the current value of x while printing and then decrements x. The for loop in C is simply a shorthand way of expressing a while statement. a).outputs:x=3 x=2 x=1 NOTE: The postfix x-. C also provides a do-while structure: do { printf("%d\n". a = a + 1. a).. suppose you have the following code in C: . For example.. Do –while loop and for loop while (a < b) { printf("%d\n". a = a + 1. Examples for While loop.

x<10. /* x++ is the same as saying x=x+1 */ } You can convert this into a for loop as follows: for(x=1. a test step (x<10). } . printf("%d\n". x++) { blah blah blah } Note that the while loop contains an initialization step (x=1). while (a < b) { a++. and an increment step (x++).a). The for loop lets you put all three parts onto one line.x=1. suppose you have the following loop: a=1. while (x<10) { blah blah blah x++. but you can put anything into those three parts. b=6. For example.

a++. &value ) == 1 && value != 0) { if (value < 0) { printf(``Illegal value\n''). break. we wish to ignore it and continue to the next value in the data. /* Abandon the loop */ } if (value > 100) . but it is possible. a < b.skip 1 iteration of loop. If the value we have read is negative. If the value is zero.You can place this into a for statement as well: for (a=1. while (scanf( ``%d''. If the value read is great than 100. The comma operator lets you separate several different statements in the initialization and increment sections of the for loop (but not in the test section). we wish to terminate the loop. 8.a)).printf("%d\n". we wish to print an error message and abandon the loop.b=6. break & continue C provides two commands to control how we loop: • • break -. continue -.exit form loop or switch. Consider the following example where we read in integer values and process them according to the following conditions. It is slightly confusing.

. for two dimensions.{ printf(``Invalid value\n''). in the above case valid subscripts range from 0 to 49. /* Skip to start loop again */ } /* Process the value read */ /* guaranteed between 1 and 100 */ ... ... This is a BIG difference between C and other languages and does require a bit of practice to get in the right frame of mind. For example. continue. Multi-dimensional arrays can be defined as follows: int tableofnumbers[50][50]... BEWARE: In C Array subscripts start at 0 and end one less than the array size. } /* end while value != 0 */ 9. ARRAYS single dimensional & Multidimensional arrays Let us first look at how we define arrays in C: int listofnumbers[50]. . listofnumbers[5]=100.. Elements can be accessed in the following ways:thirdnumber=listofnumbers[2].

For further dimensions simply add more [ ]: int bigD[50][50][40][30].. For example: int a[5].. we will use a variable arrangement called an array. but what if you needed a thousand integers? An easier way is to declare an array of five integers: int a[5]. b. . An array lets you declare and work with a collection of values of the same type. a[1] = 9. int a[5]. This is okay... tableofnumbers[25][16]=100. All arrays start at index zero and go to n-1 in C. you might want to create a collection of five integers. a[0] = 12. To do that. For example. e. We will create a small C program that generates 10 random numbers and sorts them. Thus. contains five elements. d. The five separate integers inside this array are accessed by an index.[50].. One way to do it would be to declare five integers directly: int a. c. Elements can be accessed in the following ways: anumber=tableofnumbers[2][3].

i<5. for (i=0. int i. the following code initializes all of the values in the array to 0: int a[5]. a[i]). i. a[4] = 1. The following code initializes the values in the array sequentially and then prints them out: #include <stdio. for (i=0. One of the nice things about array indexing is that you can use a loop to manipulate the index. } More on Arrays Variable Types There are three standard variable types in C: . For example. for (i=0. i++) a[i] = i.h> int main() { int a[5].a[2] = 14. int i. i++) a[i] = 0. i<5. i++) printf("a[%d] = %d\n". i<5. a[3] = 5.

the following defines a string of 50 characters: char name[50]. A float is a 4-byte floating point value. no sign bit) 10. /* Illegal */ fullname= "Mr"+firstname +lastname. firstname= "Arnold".Strings: In C Strings are defined as arrays of characters. To print a string we use printf with a special %s control character: . A char is a 1-byte single character (like "a" or "3").lastname[50]. A string is declared as an array of characters. /* Illegal */ However. There are a number of derivative types: • • • double (8-byte floating point value) short (2-byte integer) unsigned short or unsigned int (positive integers. For example.• • • Integer: int Floating point: float Character: char An int is a 4-byte integer value. /* Illegal */ lastname= "Schwarznegger".fullname[100]. C has no string handling facilities built in and so the following are all illegal: char firstname[50]. there is a special library of string handling routines which we will come across later.

.printf(``%s''.. Never forget that.. ``I''. one ASCII character per location. we require one extra storage location in the array! C does not provide any operator which manipulate entire strings at once. printf("The value of a is: %f\n". It is represented internally in C by the ASCII characters in the string. and terminated by the special null character ``\0'' so programs can find the end of the string. a). which can contain one character--1 byte--at a time. String constants are often used in making the output of code intelligible using printf . world\n"). String constants can be associated with variables. blank. char NAME[50]. Strings are manipulated either via pointers or via special routines available from the . In order to allow variable length strings the \0 character is used to indicate the end of a string. C provides the char type variable. NOTE: We just need to give the name of the string. printf("Hello. such as "I am a string" is an array of characters. since strings are conventionally terminated by the null character ``\0''. So we if we have a string. ``m''.name). i. A character string is stored in an array of character type.. and we store the ``DAVE'' in it its contents will look like: string constant . for the above string. ``a''.e.

"hello.ct.h.ct) char *strncat(s. return s char *strncpy(s.h> void main() { char line[100]. /* initialize string */ strcpy(line. c is an char converted to type int. return s -> concatenate ct to end of s. . printf("Line: %s\n".ct) char *strchr(cs. Some of the most useful functions are: char *strcpy(s.n) -> concatenate n character of ct to end of s. and n is an int. terminate with ``\0''.ct) -> copy ct into s.n) -> copy ncharcater of ct into s. *sub_text.) Consider the following code which uses some of these functions: #include < string. Using character pointers is relatively easy since the name of an array is a just a pointer to its first element.ct. return 0 if cs=ct. line).standard string library string. The standard ``string'' library contains many useful functions to manipulate strings. cs and ct are const char*. <0 if cs0 if cs>ct -> return pointer to first occurence of c -> return length of cs in cs or NULL if not encountered (s and t are char*."). return s char *strncat(s.c) size_t strlen(cs) -> compare cs and ct. including ``\0''. return s int strcmp(cs. I am a string.

sub_text). sub_text). sub_text). printf("Line: %s\n"./* add to end of string */ strcat(line. } . if ( ( sub_text = strchr ( line. 'W' ) )!= NULL ) printf("String starting with \"W\" ->%s\n". (int)strlen(line)). /* find length of string */ /* strlen brings back */ /* length as type size_t */ printf("Length of line: %d\n". line). /* find occurence of substrings */ if ( (sub_text = strchr ( line. if ( ( sub_text = strchr ( sub_text. 'u' ) )!= NULL ) printf("String starting with \"w\" ->%s\n". 'w' ) )!= NULL ) printf("String starting with \"w\" ->%s\n"." what are you?").

These stereo systems do not come in an all-in-one package. The second header takes in two integers and returns an int. tape deck. The last header doesn't return anything nor take in parameters. equalizer. and a possible parameter list. int y) void useless(void) The first function header takes in a pointer to a string and outputs a char pointer. The same concept applies to programming. because we first analyze what needs to be broken down into components. For example: . This abstract definition of a function is known as it's interface. • Some programmers like to separate returns from their function names to facilitate easier readability and searchability. cd player. Functions allow us to create top-down modular programs. Here are some sample function interfaces: • • • char *strdup(char *s) int add_two_ints(int x. and speakers. • This type of programming is known as top-down programming. • Each function consists of a name. receiver. but rather come in separate components: pre-amplifier. This is just a matter of taste. Your programs become modularized and much more readable if they are broken down into components. amplifier. The need and form of C functions • Why should we make functions in our programs when we can just do it all under main? Think for a minute about high-end stereo systems. a return type.Unit 3 1.

Functions let you chop up a long program into named sections so that the sections can be reused throughout the program.. Most languages allow you to create functions of some sort. In general. C does not care in what order you put your functions in the program. The return value must be the same type as the return type specified in the function's interface. . C functions can accept an unlimited number of parameters. return return-value.. } If return-type is omitted.....statements. int y) A function can return a single value to its caller in a statement using the keyword return.. so long as a the function name is known to the compiler before it is called. C defaults to int. in which case it has the following layout: void function-name ( argument-list-if-necessary ) { . A function may simply perform a task without returning any value. The return-value must be of the declared type. User defined and library functions User defined functions: A function has the following layout: return-type function-name ( argument-list-if-necessary ) { .. Functions accept parameters and return a result.local-declarations. 2.• • int add_two_ints(int x.

We have seen the standard I/O. Anything that extends beyond the basic language must be written by a programmer. and also makes it possible to reuse code from other programs that you write. sin etc) you must include math.h via the statement #include < math... You can use libraries in your own programs to split up your programs into modules. and debug. string handling. math functions.h> -> defining string manipulation routines < math. Library functions are generally not available to us in source form. and so on..h> -> defining mathematical routines . } Library functions: Libraries are very important in C because the C language supports only the most basic features that it needs.statements. in order to use the standard mathematical library(for function like cos. test. Argument type checking is accomplished through the use of header files (like stdio. library already: Standard libraries exist for standard I/O. time manipulation. For example.h> -> defining I/O routines < ctype.h) which contain all the necessary information. This makes them easier to understand.. The most commonly used header files are < stdio. C does not even contain I/O functions to read from the keyboard and write to the screen. as we saw earlier... or stdio. ...h> -> defining character manipulation routines < string.. The resulting chunks of code are often placed in libraries to make them easily reusable.h> at the top of the file containing your code.local-declarations.

Function Arguments C functions can accept parameters of any type. return j.h> -> defining constants of the int type < float. which is passed in as an integer parameter. Separate multiple parameters with commas: int add (int i. the following header files exist: < assert.h> -> defining diagnostic routines < setjmp.k.h> -> defining libraries to handle routines with variable numbers of arguments < time.h> -> defining number conversion.< stdlib.h> -> defining constants of the float type 3.h> -> defining non-local function calls < signal.h> -> defining signal handlers < limits. storage allocation and similar tasks < stdarg. for (k=2. } returns the factorial of i. j=1. k<=i. } .h> -> defining time-manipulation routines In addition. k++) j=j*k. int j) { return i+j. For example: int fact(int i) { int j.

unless you know you will be shipping the code to someone who has access only to an "old style" (non-ANSI) compiler. You should use the "new style. it is just a different notation. parameterdef2. There is no difference in the way it executes. Return values returntype fn_name(1.You will sometimes see functions such as add written in the "old style. float b) { float average. 4. return(average). { return i+j. { localvariables functioncode } Let us look at an example to find the average of two integers: float findaverage(float a." (known as ANSI C) with the type declared as part of the parameter list.j) int i. } It is important to be able to read code written in the older style. } ) ." as shown below: int add(i. average=(a+b)/2. int j.

printf("%d\n".b=15.result. main can call function1. which calls function2. 5. for (loop=1. } Note: we can return only single value at a time.b). Nesting of function C permits nesting of functions freely.loop++).loop*loop). Example: .loop<10.We would call the function as follows: main() { float a=5. printf("average=%f\n". } main() { squares(). result=findaverage(a. } Note: We must have () even for no parameters unlike some languages. which calls function3. ………and so on. If you do not want to return a value you must use the return type void and miss out the return statement: void squares() { int loop.result).

ratio(a.b. } 6. Recursion When a called function in turns calls another function a process of ‘chaining’ occurs. printf(“%f”\n”. scanf(“%d %d %d”. float ratio(). else return 0.0). &a.&c). } difference(p. else return(0.q) int p. { if(p!=q) return 1.c.main() { int a.z) int x.y. { if(difference(y. A very example is: main() .c)).b. where a function calls itself.y. &b. } float ratio(x.q. Recursion is a special case of this process.z.z)) return(x/(y-z)).

Any change made to the arguments internally in the function are made only to the local copies of the arguments. Calling of function The call to a function in C simply entails referencing its name with the appropriate arguments. return fact. Another useful example is of factorial: factorial of n = n(n-1)(n-2)……. This means that local ``copies'' of the values of the arguments are passed to the routines. Arguments are always passed by value in C function calls. . } 7. In order to change (or define) an argument in the argument list.{ printf(“This is an example of recursion\n”). main() } This execution will continue indefinitely.1 for example factorial of 4 = 4*3*2*1=24 factorial(int n) { int fact. if(n==1) return. this argument must be passed as an address. The C compiler checks for compatibility between the arguments in the calling sequence and the definition of the function. thereby forcing C to change the ``real'' argument in the calling routine. else fact=n*factorial(n-1).

b = %d\n". printf("From main: a = %d. a = b. First let's illustrate what happen if the variables are passed by value: #include < stdio.As an example. } void exchange(int a. b). b = temp. a. } Run this code and observe that a and b are NOT exchanged! Only the copies of the arguments are exchanged. void main() { int a. printf("Back in main: ").h> void exchange(int a. int b) { int temp. printf(" From function exchange: "). b. b). a = 5. The RIGHT way to do this is of course to use pointers: /* WRONG CODE */ . consider exchanging two numbers between variables. printf("a = %d. temp = a. printf("a = %d. b = 7. a. exchange(a. b). a. b = %d\n". b). int b). b = %d\n".

printf("From main: a = %d. temp = *a. printf("a = %d. b = %d\n".#include < stdio. printf("a = %d. You can call it with the following statement: . *b). exchange(&a. printf("Back in main: "). a. &b). printf(" From function exchange: "). b). void main() { int a. a. b. b = %d\n". *b = temp. int *b ).h> void exchange ( int *a. int *b ) { int temp. b). *a. a = 5. *a = *b. b = %d\n". } void exchange ( int *a. b = 7. } The rule of thumb here is that • /* RIGHT CODE */ You use regular variables if the function does not change the values of those arguments You MUST use pointers if the function changes the values of those arguments • If the function returns no value.

} Here the declaration float list[] tells C that list is an array of float.x<xsize. printf("\n"). Note we do not specify the dimension of the array when it is a parameter of a function. 8.y++) printf("\t%f".int ysize. If you do not. float sum=0.function_name(). Multi-dimensional arrays can be passed to functions as follows: void printtable(int xsize.table[x][y]). for (x=0. float table[][5]) { int x.0.i++) sum+=list[i]. return(sum/size).x++) { for (y=0. even though it will compile correctly on many systems. Array as function argument Single dimensional arrays can be passed to functions as follows:float findaverage(int size.i<size.y. for (i=0.y<ysize. You must include () in the call. } } . the function is not called.float list[]) { int i.

Scope and life of variables(local and global variables) Local variables: These are the variables which are declared inside the functions.Here float table[][5] tells C that table is an array of dimension N BUT not the first dimension. add=a+b. return add. Example int add. There scope is local to that function. 5 of float. int b) { add= a+b. Scope is in all functions. They do not exist outside that function. Global variables: These are the variables which are declared outside the functions. int b) { int add. Note we must specify the second (and subsequent) dimension of the array 9. } Here add is local variable of function sum We can’t access its value outside this function. } . void sum(int a. Example: int sum(int a.

E. the variable . volatile is used less frequently and tells the compiler that this value can be modified outside the control of the program.register A. register.static. int i. H. If you declare a static variable inside a function.extern. signed. This is usually implicit in most variable declarations. F. double are the fundamental data types in C. D.Storage class specified-auto. G. static. The extern keyword makes the specified variable access the variable of the same name from some other file. Not all combinations of types and modifiers are available. Type qualifiers include the keywords: const and volatile. B. int. The auto keyword places the specified variable into the stack area of memory. The const qualifier places the assigned variable in the constant data area of memory which makes the particular variable unmodifiable (technically it still is though). extern.g. float. C. e.Here add is global variable 10. unsigned. The register keyword suggests to the compiler to place the particular variable in the fast register memory located directly on the CPU. Type modifiers include: short. This is very useful for sharing variables in modular programs. Storage classes include: auto. char. The static keyword is useful for extending the lifetime of a particular variable. Most compilers these days (like gcc) are so smart that suggesting registers could actually make your program slower. long.

A string is NOT a type directly supported by C.remains even after the function call is long gone (the variable is placed in the alterable area of memory). You. therefore. cannot "assign" stuff into strings. .. We will go more in-depth with strings later. A string is defined by ANSI as an array (or collection) of characters. The static keyword is overloaded.. static can also be used with functions. making those functions visible only to the file itself. I. It is also used to declare variables to be private to a certain file only when declared with global variables.

You can think of a structure as a "record" is in Pascal or a class in Java without methods. are very useful in creating data structures larger and more complex than the ones we have discussed so far. student_b. char SSN[10]. float gpa. char **classes. So how is a structure declared and initialized? Let's look at an example: struct student { char *first. struct student student_a. } student_a. or structs. char *last. . Another way to declare the same thing is: struct { char *first.Unit 5 1. }. We will take a cursory look at some more complex ones in the next section. Defining structure & declaration of structure variable A structure in C is a collection of items of different types. char *last. char **classes. char SSN[9]. student_b. • Structures. float gpa.

char SSN[9]. Create lists of students). if you wanted to declare another struct later. For example: typedef struct { char *first. float gpa. you couldn't. The pointer allows us greater flexibility (e. char **classes.As you can see. char *last. *pstudent. Now we have created a student_t student and a student_t pointer. The "better" method of initializing structs is: struct student_t { char *first. char **classes. char *last. student student_a.g. char SSN[10]. Now we get rid of those silly struct tags. float gpa. You can use typedef for nonstructs: . • There is an easier way to define structs or you could "alias" types you create. } student. But in the second case. } student. the tag immediately after struct is optional.

.2. and: itscalibre=arniesguns[0]. agun arniesguns[1000]. to assign the SSN of student_a: strcpy(student_a. 4.calibre. float calibre. This gives arniesguns a 1000 guns.SSN. gives Arnie's gun number 50 a calibre of 100mm. For example. assigns the calibre of Arnie's first gun to itscalibre. "111223333\0"). Array of structures C also allows arrays of structures: typedef struct gun { char name[50]. } agun. int magazinesize. Nested structures Refer to unions Structures can be nested in the similar way. (period). Accessing structure members But how do we access fields inside of the structure? C has a special operator for this called "member of" operator denoted by .calibre=100. This may be used in the following way: arniesguns[50]. 3.

{ --------------------------------------------- . The actual arguments are then treated independently like ordinary variables. In this case. It is therefore necessary for the function to return the entire structure back to the calling function. Here we will discuss the second method: The general format is: function_name (structure_variable_name) The called function takes the following form data_type function_name ( st_name) struct_type st_name. Method 3: The third approach employs a concept called pointers to pass the structure as an argument.5. Method1: To pass each member of the structure as an actual argument of the function call. Since the function is working on a copy of the structure. Method 2: The second method involves passing copy of the entire structure to the called function. Structure and Function C supports the passing of structure values as argument to functions. There are three methods by which the values of structure can be transferred from one fuction to other. the address location of the structure is passed to the called function. The function can access indirectly the entire structure and work on it. any changes to structure members within the function are not reflected in the original structure.

For example. c. if it is placed after the calling function. The return statement is necessary only when the function is returning some data. then it must be declared as struct with an appropriate tag name. double floatnumber. } Note: a. The expression many be any simple variable or structure variable or an expression using simple variable. The structure variable used as the actual argument and the corresponding formal argument in the called function must be of the same struct type.return expression. C uses the union statement to create unions. long longnumber. The called function must be declared in the calling function for its type. for example: union number { short shortnumber. if it is returning a copy of entire structure. d. 6. When a function returns a structure. it must be assigned to a structure of identical type in the calling function. e. The called function must be declared for its type. appropriate to the data type it is expected to return. b. } anumber . Union A union is a variable which may hold (at different times) objects of different sizes and types.

} jet. typedef struct { int liftcapacity.anumber. In order that the program can keep track of the type of union variable being used at a given time it is common to have a structure (with union embedded in it) and a variable which flags the union type: An example is: typedef struct { int maxpassengers.longnumber). } helicopter. } cargoplane. . number is a union tag and acts in the same way as a tag for a structure. This clearly displays the value of longnumber. helicopter helicopteru. typedef struct { int maxpayload.defines a union called number and an instance of it called anumber. When the C compiler is allocating memory for unions it will always reserve enough room for the largest member (in the above example this is 8 bytes for the double). typedef union { jet jetu. Members can be accessed in the following way: printf("%ld\ n".

. Why you ask? An example first: struct conditions { float temp. union feels_like { float wind_chill. Only one item within the union can be used at any time. because the memory allocated for each item inside the union is in a shared memory location. int speed. } aircraft. } } today. } an_aircraft.cargoplane cargoplaneu. typedef struct { aircrafttype kind. float heat_index. In the an_aircraft structure there is a kind member which indicates which structure is being held at the time. helicopter. This example defines a base union aircraft which may either be jet. aircraft description. or cargoplane. • Unions are declared in the same fashion as structs. but have a fundamental difference.

feels_like only has one value. . wind_chill is only calculated when it is "cold" and heat_index when it is "hot". There is no need for both. • Types inside of unions are unrestricted. either a float for wind_chill or a float for heat_index. So when you specify the temp in today. you can even use structs within unions.As you know.

Sign up to vote on this title
UsefulNot useful