Looping
Suppose you have two bucket A and B. Bucket A is full of water and Bucket B is empty. One empty Jug is given to you. If I ask you to fill the bucket B by taking water from Bucket A. You will fill Jug from Bucket A and put water in bucket B. You will repeat this process of taking water from bucket A and putting that water into Bucket B till bucket B is full. To implementing repetition of same process C provide us various types of Looping technique.
Following are the types of loops available in C.
1) For Loop
2) While Loop
3) Do While loop
1) For loop
for loop has below syntax:
for(expr1,expr2,expr3)
{
statements;
}
overview of for loop
- execute expression 1 and assume it as base.
- execute expression 2 and check the result of expression 2. If result is positive execute statement inside the for block.
- at the end of for block execute expr3
- repeat above 3 step till we get expression 2 result is false.
example For Loop:
for(i=0;i<10;i++)
{
printf(“hello”);
}
- i initialize to 0.
- as i is less than 10 so result is true and hence go inside for block
- print “hello”
- increment i with 1
- now value of i is 1
- value of i is still less than 10 and hence go inside for block
- print “hello”
- repeat step 1 to 3 till value of i doesn’t reach greater than or equal to 10.
- as an output we will get “hello” printed 10 times.
other example of while loop:
for(;;)
{
printf(“hello”);
}
This example of for loop is infinite loop as we don’t have expr2 in for loop or we can say that we don’t have any terminating condition so loop will go infinite.
for(exp1;;exp3)
{
printf(“hello”);
}
This loop is also infinite loop for the same reason as discussed above.
While Loop:-
in while loop we check first terminating condition if its result is true then only we enter into loop otherwise loop exists. below is the syntax for while loop
while(exp1)
{
statements;
}
- first exp1 is executed .
- if value of exp1 is true then statements of while block will be executed and go to step 1.
- else we won’t be allowed to enter in loop and loop exist.
example of while loop
i=0;
while(i<10)
{
printf(“hello”);
i++;
}
- compare value of i with 0. As it less than 10 and hence result of comparison is positive enter in while loop.
- print “hello”
- increment value of i by 1.
- now value of i is 1.
- again compare the value of i with 10.As result of comparison is positive enter into loop and execute statements inside loop.
- execute first three steps till value of i less than 10.
following are other example:
while() //compile time error
{
statement;
}
this loop will give compile time error as in C while loop is not allowed with terminating statement or without exp1.
while(1)
{
statements;
}
this loop is infinite loop as exp1 will be always positive and we won’t get any terminating condition so this loop will go infinite.