# 7.

Loops & Control Constructs

1

Loops
Loop with ³if´ using goto and label Example : Demonstrates use of if for iteration #include <stdio.h> int main() { int sum=0, i=1; /*declaration and initialization combined*/ Step3: /*label- loop starts here*/ if (i<=10)
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 2

Loops (Contd.)
{ sum= sum+i; i=i+1; goto step3; } printf(³sum of first 10 natural numbers=%d\n´, sum); } Result: sum of first 10 natural numbers=55
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 3

for statement
for (exp1; exp2; exp3) {statements; } Note the keyword, the parentheses and semicolons. No semicolon after exp3. exp1, exp2 and exp3 are expressions. exp1 ± contains the initial value of an index or a variable. exp3 ± contains the alteration to the index after each iteration of the body of the for statement.
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 4

for statement (Contd.)
The body of the statement is either a single statement or group of statements enclosed within braces. If a single statement has to be executed then braces are not required. exp2 ± condition that must be satisfied if the body of statements are to be executed. An example of a for loop is given below: for (i=0; i<5; i++) printf(³%d´, i);
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 5

Finding sum of first 10 natural numbers
int main() { int sum=0, i=0; /*declaration and initialization combined*/ for (i=1; i<=10; i++) /*loop starts here*/ { sum=sum+i; } printf(³sum of the first 10 natural numbers=%d\n´, sum); } Result: sum of first 10 natural numbers=55
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 6

Exercise
What change will you make if we want to add 100 numbers and 1000 numbers ?

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

7

Three Components of for
exp1 and exp3 are assignments or function calls. exp2 is a relational expression. The three expressions may not always be present. However, even if an expression is not present, the associated semicolon should be present. For instance, for (;exp2;) {s1}
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 8

Finding all even numbers
int main () { int i=2; for (; i<50; i+=2) /*loop starts here*/ { printf(³%i is an even number\n´, i); } }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 9

Symbolic Constants
# define name constant Not variables and hence they are not defined as part of the declarations of variables. Specified on top of the program before the main() Wherever the symbolic constant names appear in the program, the compiler will replace them with the corresponding replacement constants.

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

10

Symbolic Constants (Contd)
#define LOW 100 #define UPPER 150 #define STEP 1

int main()
{ int num; for (num=LOW; num<UPPER; num+=STEP) /*loop starts here*/ { if(num%3 == 0) printf(³%i is evenly divisible by 3\n´, num); } }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 11

Nested for Loop
Example for (i=1;i<=10; i++) { for (j=1; j<=5; j++) { for (k=1; k<=2; k++) { s1 } } }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 12

while loop 
Subset of for loop { exp1; while (exp2) { statements exp3; }}

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

13

Generation of Multiplication Table
int main() { int a,b,product; a=1; b=0; product=0; printf(³Enter which table you want´); scanf(³%d´, &b)¶ while (a <=10) { product = a*b; printf(³%2d X %d= %3d\n´,a,b,product); a++; } }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 14

Reversing a number
#include <stdio.h> int main() { long unsigned n, reverse; printf(³enter the number to be reversed\n´); scanf(³%lu´, &n); reverse=0; while (n>0) { reverse=reverse*10+ (n%10); n=n/10; } printf(³Reversed number=%lu´, reverse); }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 15

Structure of while

TRUE

While condition

FALSE

STATEMENTS STATEMENTS

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

16

do«. while
DO

STATEMENTS

TRUE
While condition

FALSE

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

17

Example of do«.while
#include <stdio.h> #include<conio.h> main() { int alpha=0; do { printf (³\nenter upper case alphabet- enter 1 to quit\n´); if (alpha >=µA¶ && alpha<=µZ¶) { alpha=(alpha+32); putch(alpha); }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 18

Example of do«.while
else { if(alpha==µ1¶) printf(³End of Session´); else printf(³\ninvalid entry; retry´);

} }while(alpha!=µ1¶); }

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

19

Linear Search
Algorithm Declaration array ia of size n, i = 0 item to be searched = x found = false do if (ia[i] == x) then found = true else i=i+1 while (i<= n ± 1 && not found)
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 20

Switch
 Enables multi-way decision making  More powerful than if .. else  Syntax of switch statement is given below. switch (expression) { case constant or expression : statements case constant or expression : statements .. Default : statements } Constant expressions following case should be unique.
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 21

Example of Switch
int main() { int a; char ch = µc¶; while (ch==µc¶) { printf(³\nEnter a digit 0 to 9\n´); scanf(³%d´,&a); switch(a) { case 0:printf(³Zero\n´); break;
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 22

Example of Switch (contd.)
case 1:printf(³One\n´); break; case 2:printf(³Two\n´); break; case 3:printf(³Three\n´); break; case 4:printf(³Four\n´); break; case 5:printf(³Five\n´); break; case 6:printf(³Six\n´); break;
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 23

Example of Switch (contd.)
case 7:printf(³Seven\n´); break; case 8:printf(³Eight\n´); break; case 9:printf(³Nine\n´); break; default:printf(³Illegal character\n´); } printf(³enter µc¶ if you want to continue\n´); printf(³or any other character to end\n´); ch=getche(); if(ch!=µc¶) printf(³End of Session´); } }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 24

Switch with char
char m; switch(m) { case µa¶ : s1; break; case µb¶ : s2; break ; }

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

25

SWITCH with char (contd.)
int op; switch(op) { case µ+¶ : s1; break; case µ/¶ : s2; break ; }

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

26

Break, Continue, Return
 Break causes the program to break from the loop that encloses it and proceed to the next stage of the program  Continue causes resuming next iteration of the loop.  Return may appear anywhere in the program int main() { int a; do { printf(³enter a number-enter 0 to end session\n´); scanf(³%d´, &a); if(a>20000) { printf(³you entered a high value-going out of range\n´); break; }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 27

Break, Continue, Return (contd)
else if(a>0) printf(³you entered %d\n´, a); if (a<0) { printf(³you entered a negative number\n´); continue; } } while(a!=0); printf(³End of session\n´);
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 28

Result of program
Enter a number-enter 0 to end session 33 You entered 33 Enter a number-enter 0 to end session -60 You entered a negative number Enter a number-enter 0 to end session 45 You entered 45 Enter a number-enter 0 to end session 25000 You entered a high value-going out of range End of session * exit() function
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 29

8. Arrays

30

Arrays
 User defined data type  Contains data of the same type  Array of integers, array of double etc. A = {2,4,6,8} A[0]=2 A[1]=4 A[2]=6 A[3]=8

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

31

Array Declaration
Eg. double emp_age [100];  allots memory size of 100 doubles contiguously.  If emp_age[0] is stored in location 1000 then emp_age[n] will be stored in 1000 + n * 8 (size of variable). [100] is called subscript. Initialization
Double emp_age[5] = {30.1, 31.1, 35.1, 36.1, 37.1]; Double emp_age[] = {30.1, «.. 37.1};

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

32

Getting, storing and printing ten integers
{ int s1[10]; int i; printf(³Enter 10 integers \n´); for (i=0; i<=9; i++) { } printf(³you have entered:\n´); for (i=0; i<=9; i++) { printf(³%d\n´, sl[i]); }}
33

scanf(³%d´, &s1[i]);

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

Finding greatest number and position in a Array
int main() { int a[5]={1,5,2,6,3}; int max=0, i, ind=0; for(i=0; i<=4; i++) { if (a[i] > max) { max =a[i]; ind=i+1; }

} printf(³maximum number=%d location=%d\n´, max,ind); }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 34

Strings
 String is an array of characters  char name{25};  scanf(³%s´, name);  The syntax for gets is: gets(name); puts(name); puts (³Enter the word´);  printf canbe used to print more than one variable and scanf to get more than one variable at a time, in a single statement. However, puts can output only one variable and gets can input only one variable in one statement. In order to input or output more than one variable, separate statements have to be written for each variable. gets and puts are unformatted I/O functions  Use <string.h> to use string related library functions Eg. strlen(str) returns length of str.
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 35

Palindrome
#define FALSE 0 int main() { int flag=1; int right, left, n; char w[50]; /* maximum width of string 50*/ puts(³Enter string to be checked for palindrome´); gets(w); n=strlen(w)-1; for ((left=0, right=n); left<=n/2; ++left, -right) { if (w[left] !=w[right]) { flag=FALSE; break;} }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 36

Palindrome
if (flag) { puts(w); puts(³is a palindrome´); } else printf(³%s is NOT a palidrome´); }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 37

Multi-Dimensional Arrays
 Multi-dimensional Arrays are stored row by row continuously. int main() { int i,j; int z[2][2]; int x[2][2] = {1,2,3,4}; int y[2][2] = {5,6,7,8}; for (i=0; i<=1; i++) { for (j=0; j<=1; j++) { } }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 38

z[i][j]=x [i][j] * y[i][j]; printf(³z[%d][%d]=%d\n´, i, j, z[i][j]);}

Binary Search
Pre-condition : Data already sorted. Algorithm for Binary Search int a[n]; left = 0 right = n-1 found = false; while (left<right) {mid = (left+right)/2; if (a (mid) = =x) found = true; else if (a(mid) < x) left = mid + 1; else right = mid;} if (found) print (³found´); else print (³Not found´);
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 39

9. Functions

40

Modular Programming Concept
MAIN

f1

f2

f3

f4

f11

f12

f21

f31

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

41

Structured programming ± Code of good programming practices 
Write only one statement per line  Coin meaningful names for constants, variables and functions  Use capitals for names of constants  Divide programs into functions  Each function performs one task  Each function must have atleast one comment statement  Skip a line between functions  Skip a line after declaration statements in the main function as well as each function
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 42

Structured programming ± Code of good programming practices 
Bring clarity by skipping lines wherever required  Put only one brace on each line  Align all opening braces and closing braces  Indent as much as possible to bring out logical structure of the program  Some of the program statements that could be indented are body of function, body of loop, body of if..else statements  Indent each case in switch statement  Indent an item within a structure declaration.
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 43

Three Parts of Function
A function consists of three parts : a) Function Declaration b) Function Definition c) Function Call

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

44

Function Declaration
return data ± type function name (formal argument 1, argument 2,«. ) ; Example float f1 (float arg 1, int arg 2); void fun2 (float arg1, int arg2); /*void means nothing*/ char fun3(float arg1, int arg2); char fun4(); Also called function prototype.
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 45

Function Call
     Function can be called directly or indirectly. Eg. Fun1(25); sum = fin1(25); Function call made by passing actual arguments. Function call must be in conformity with function proto. Return type not to be specified.
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 46

Function Definition
  Can be located anywhere. Consists of 2 parts ±  Function declarator or header  Conforms to proto, no semicolon  Function body  Consists of local variables & statements

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

47

main function Step 1 Step 2 Step 3 Step 4 Step 5 Step 1 Step 2 Step 3 define function add get 2 integers call add & pass the 2 values get the sum Print the value Function Add get the values add them return the value to main function
48

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

int main() { int a=0, b=0, sum=0; int add(int x, int y); /*function declaration*/ printf(³enter 2 integers\n´); scanf(³%d%d´, &a, &b); sum=add(a,b); /*functon call*/ printf(³sum of %d and %d=%d´, a,b,sum); /* function definition*/ Int add (int c, int d) /* function declarator*/ { int e; e=c+d; return e; }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

}

49

Function - Important Points
 Function declarator is a replica of the function declaration  The only difference is that the declaration in the calling function will end with a semicolon and the declarator in the called function will not end with a semicolon.  The declarator must agree totally with the declaration in the called function i.e.the return data type, the function name, the argument type should all appear in the same order.  When the function encounters the closing brace }, it returns control the calling program and returns to the same place at which the function was called.
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 50

A Function called many times
{ float a,b,c,d, sum1, sum2, sum3; float add(float a, float b); /* function declaration*/ printf(³enter 2 float numbers\n´); scanf(³%f%f´, &a, &b); sum1 = add(a,b); /*function call*/ printf(³enter 2 more float numbers\n´); scanf(³%f%f´, &c, &d); sum2 = add(c,d); /* function call*/ sum3=add(sum1,sum2); printf(³sum of %f and %f=%f\n´, a,b,sum1); printf(³sum of %f and %f=%f\n´, c,d,sum2); printf(³sum of %f and %f=%f\n´, sum1,sum2,sum3); } /*function definition*/ float add (float c, float d) /* function declarator*/ { float e; e=c+d; return e; }
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 51

Calling multiple functions
Step 1 : get the number Step 2 : if number is odd call the Reverse function Step 3 : else multiply the number by 2 Step 4 : if number is evenly divisible by 3 call ADD-digits Reverse Function Step 1 : reverse = 0 Step 2 : while (number > 0) reverse = reverse * 10 + (number % 10) number = number/10 Step 3 : return (reverse)

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

52

Calling multiple functions (Contd.)
ADD-digits function Step 1 : sum = 0 Step 2 : while number > 0 sum = sum + (number % 10) number = number / 10 Step 3 : return (sum) Look at Example 44 in page 146.
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 53

Scope rules for functions
Scope of the variable is local to the function, unless it is global Look at Example 45 in page 149. To find the greatest number in an array, look at Example 46 in page 151. To reverse a string, look at Example 47 in page 152.

R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi

54

Return values
return (sum); return v1; return ³true´; return `Z¶; return 0; return 4.0 + 3.0; etc. return;
R. Subburaj, ³Programming in C´ © Vikas Publshing House Pvt. Ltd, New Delhi 55