UNIT- 3
Loops & Functions
Iteration statements create loops in the program. In other words, it repeats the set of statements until the condition for termination is met. Iteration statements in C are for, while and do-while. while statement The while loop in C is the most fundamental loop statement. It repeats a statement or block while its controlling expression is true. The general form is: while(condition) { // body of loop } The condition can be any boolean expression. The body of the loop will be executed as long as the conditional expression is true. Here is more practical example. //example program to illustrate while looping #include <stdio.h>
int main () { int n = 10; while (n > 0) { printf("tick %d", n); printf("\n"); n--; } } The output of the program is: tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 3.1.1 use of while, do while and for loops The for loop The for loop executes repeatedly until the condition specified in for loop is satisfied. When the condition becomes false it resumes with statement written in for loop. Structure of the for loop:
Initialization is the assignment to the variable which controls the loop. Condition is an expression, specifies the execution of loop. Increment/ decrement operator changes the variable as the loop executes. e.g.
Output is 1 2 3 4 5. The Nested for loop. Nested for loop is for within for loop.
Structure of the nested for loop:
The while Loop The while loop consists of a condition with set of statements. The Execution of the while loop is done until the condition mentioned in while is true. When the condition becomes false the control comes out of loop. Structure of the while loop:
e.g.
X is initialized to 1. The loop will execute till x<=6. Output will be 1 2 3 4 5 6 7 8 9 10. The do – while loop The do – while loop consist of consist of condition mentioned at the bottom with while. The do – while executes till condition is true. As the condition is mentioned at bottom do – while loop is executed at least once. Structure of the do – while:
e.g.
Output is: 1 2 3 4 5 6 7 8 9 10.
3.1.2 Multiple loop variables C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept. Syntax The syntax for a nested for loop statement in C is as follows − for ( init; condition; increment ) {
for ( init; condition; increment ) { statement(s); } statement(s); } 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 any other type of loop. For example, a ‘for’ loop can be inside a ‘while’ loop or vice versa. Example The following program uses a nested for loop to find the prime numbers from 2 to 100 #include <stdio.h> int main () {
/* local variable definition */ int i, j; for(i = 2; i<100; i++) { for(j = 2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime\n", i); }
return 0; } When the above code is compiled and executed, it produces the following result − 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime
3.1.3 Use of break and continue statements The break The break statement is used to terminate the execution where number of iterations is not unknown. It is used in loop to terminate the loop and then control goes to the first statement of the loop. The break statement is also in switch case. Structure of the break:
e.g.
When the compiler will reach to break it will come out and print the output. Output will be x=1,x=9,x=8,x=7,x=6,break. The continue The continue statement work like break statement but it is opposite of break. The Continue statement continue with execution of program by jumping from current code instruction to the next. Structure of the break:
e.g.
Output is 1 2 3 4 5.
|
Similar to other languages C language also provides the facility of function. Function is the block of code which is used to perform a specific task. In c language the complete program is composed of function. Functions are useful to divide c programs into smaller modules. Programmer can invoked these modules anywhere inside c program for any number of times. Functions are used to increase readability of the code. Size of program can be reduce by using functions. By using function, programmer can divide complex tasks into smaller manageable tasks and test them independently before using them together. Functions of C language are defined with the type of function. The type of functions indicates the data type of value which will return by function. In order to use function in the program, initially programmer have to inform compiler about the function. This is also called as defining a function. In C program all the function definition present outside the main function. All function need to be declared and defined before use. Function declaration requires function name, argument list, and return type.
3.2.1 Introduction Similar to other languages C language also provides the facility of function. Function is the block of code which is used to perform a specific task. In c language the complete program is composed of function. Functions are useful to divide c programs into smaller modules. Programmer can invoked these modules anywhere inside c program for any number of times. Functions are used to increase readability of the code. Size of program can be reduce by using functions. By using function, programmer can divide complex tasks into smaller manageable tasks and test them independently before using them together. Functions of C language are defined with the type of function. The type of functions indicates the data type of value which will return by function. In order to use function in the program, initially programmer have to inform compiler about the function. This is also called as defining a function. In C programme all the function definition present outside the main function. All function need to be declared and defined before use. Function declaration requires function name, argument list, and return type. Return Type Function name (Argument list) { Statement 1; Statement 2; …………... Statement n; }
3.2.2 Types of functions 1. Library Functions A function which is predefined in c language is called library function. Library function is also called as built in function of C language. The definition of library function is stored in respective header file. Library functions are used to perform dedicated operation like taking input from user, displaying output, string handling operation, etc. Library functions are readily available and programmer can directly use it without writing any extra code. For example, printf () and scanf () are library function and their definition is stored in stdio header file. 2. User Defined Functions User define function is the block of code written by programmer to perform a particular task. As compiler doesn’t have any idea about the user define function so programmer has to define and declare these functions inside the program body. Programmer can define these function outside the main function but declaration of user define function should present in main function only. Whenever compiler executes function call (function declaration) then compiler shift the flow of program execution to the definition part of user define function. Example #include <stdio.h> #include<conio.h> int add (int x, int y) { int sum; sum = x + y; return (sum); } main () { int a,b,c; a = 15; b = 25; c = add(a,b); printf ("\n Addition is %d ", c); } Output: Addition is 40 There are two ways to pass the parameters to the function
In this mechanism, the value of the parameter is passed while calling the function. 2. Parameter Passing by reference In this mechanism, the address of the parameter is passed while calling the function. 3.2.3 Functions with array Array is a data structure which stores the collection of similar types of element in consecutive memory locations. Indexing of array always start with ‘0’ where as non-graphical variable ‘\0’ indicates the end of array. Syntax for declaring array is data type array name[Maximum size];
Example:
This is the default way of passing the parameters to the function. This is achieved by passing the copy of data to the function. This mechanism is also called as call by value. In case of parameter passing by value, the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. This mechanism is used when programmer don't want to change the value of passed parameters. When parameters are passed by value then functions in C create copies of the passed in variables and do required processing on these copied variables. Pass-by-value is implemented by actual data transfer so additional storage is required to maintain the copies of passed parameters. Example: #include <stdio.h> #include<conio.h> /* function declaration goes here.*/ void swap( int p1, int p2 ); int main() { int a = 10; int b = 20; printf("Before: Value of a = %d and value of b = %d\n", a, b ); swap( a, b ); printf("After: Value of a = %d and value of b = %d\n", a, b ); getch(); } void swap( int p1, int p2 ) { int t; t = p2; p2 = p1; p1 = t; printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 ); } Output : Before: Value of a = 10 and value of b = 20 Value of a (p1) = 20 and value of b (p2) = 10 After: Value of a = 10 and value of b = 20
3.2.4 Passing parameters to functions, Call by value Parameter Passing by Value This is the default way of passing the parameters to the function. This is achieved by passing the copy of data to the function. This mechanism is also called as call by value. In case of parameter passing by value, the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. This mechanism is used when programmer don't want to change the value of passed parameters. When parameters are passed by value then functions in C create copies of the passed in variables and do required processing on these copied variables. Pass-by-value is implemented by actual data transfer so additional storage is required to maintain the copies of passed parameters. Example: #include <stdio.h> #include<conio.h> /* function declaration goes here.*/ void swap( int p1, int p2 ); int main() { int a = 10; int b = 20; printf("Before: Value of a = %d and value of b = %d\n", a, b ); swap( a, b ); printf("After: Value of a = %d and value of b = %d\n", a, b ); getch(); } void swap( int p1, int p2 ) { int t; t = p2; p2 = p1; p1 = t; printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 ); } Output : Before: Value of a = 10 and value of b = 20 Value of a (p1) = 20 and value of b (p2) = 10 After: Value of a = 10 and value of b = 20 Note: In the above example the values of “a” and “b” remain unchanged before calling swap function and after calling swap function. Parameter Passing by Reference This mechanism is used when programmer want a function to do the changes in passed parameters and reflect those changes back to the calling function. This mechanism is also called as call by reference. This is achieved by passing the address of variable to the function and function body can directly work over the addresses. Advantage of pass by reference is efficiency in both time and space. Whereas disadvantages are access to formal parameters is slow and inadvertent and erroneous changes may be made to the actual parameter. Example: #include <stdio.h> #include<conio.h> void swap( int *p1, int *p2 ); int main() { int a = 10; int b = 20; printf("Before: Value of a = %d and value of b = %d\n", a, b ); swap( &a, &b ); printf("After: Value of a = %d and value of b = %d\n", a, b ); } void swap( int *p1, int *p2 ) { int t; t = *p2; *p2 = *p1; *p1 = t; printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 ); } Output : Before: Value of a = 10 and value of b = 20 Value of a (p1) = 20 and value of b(p2) = 10 After: Value of a = 20 and value of b = 10 Note: In the above example the values of “a” and “b” are changes after calling swap function.
3.2.5 Call by reference Array is a data structure which stores the collection of similar types of element in consecutive memory locations. Indexing of array always start with ‘0’ where as non-graphical variable ‘\0’ indicates the end of array. Syntax for declaring array is data type array name[Maximum size];
Example:
This is the default way of passing the parameters to the function. This is achieved by passing the copy of data to the function. This mechanism is also called as call by value. In case of parameter passing by value, the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. This mechanism is used when programmer don't want to change the value of passed parameters. When parameters are passed by value then functions in C create copies of the passed in variables and do required processing on these copied variables. Pass-by-value is implemented by actual data transfer so additional storage is required to maintain the copies of passed parameters. Example: #include <stdio.h> #include<conio.h> /* function declaration goes here.*/ void swap( int p1, int p2 ); int main() { int a = 10; int b = 20; printf("Before: Value of a = %d and value of b = %d\n", a, b ); swap( a, b ); printf("After: Value of a = %d and value of b = %d\n", a, b ); getch(); } void swap( int p1, int p2 ) { int t; t = p2; p2 = p1; p1 = t; printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 ); } Output : Before: Value of a = 10 and value of b = 20 Value of a (p1) = 20 and value of b (p2) = 10 After: Value of a = 10 and value of b = 20 Note: In the above example the values of “a” and “b” remain unchanged before calling swap function and after calling swap function.
3.2.6 Recursive functions In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); } The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers has to be careful to define an exit condition from the function, otherwise it will go into an infinite loop. Recursive functions are useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc. The following example calculates the factorial of a given number using a recursive function − #include <stdio.h> unsigned long long int factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 12; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; } When the above code is compiled and executed, it produces the following result − Factorial of 12 is 479001600 The following example generates the Fibonacci series for a given number using a recursive function − #include <stdio.h> int fibonacci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonacci(i-1) + fibonacci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%d\t\n", fibonacci(i)); } return 0; } When the above code is compiled and executed, it produces the following result − 0 1 1 2 3 5 8 13 21 34 |
References:
- The C Programming Language. 2nd Edition Book by Brian Kernighan and Dennis Ritchie
- C Programming: A Modern Approach Book by Kim N. King
- C Programming Absolute Beginner’s Guide book by S.D Perry