Friday, 21 June 2013

Different's Between 'for' and 'while' loop


For a compiling a program there is nothing different's between 'for' and 'while', but while using the programming certain business logic we may have the different's. The following examples will explain the different's of 'for' and 'while'.

For loop: When it is desired to do initialization, condition check and increment/decrements in a single statement of an iterative loop, it is recommended to use 'for' loop.
// Syntax
for(initialization;condition;increment/decrements)

{
    //block of statements
}
Program: Program to illustrate for loop
#include<stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
// print the number
printf ("%d", i);
}
return 0;
}

Output:12345
Explanation:
The loop repeats for 5 times and prints value of 'i' each time. 'i' increases by 1 for every cycle of loop. 
while loop: When it is not necessary to do initialization, condition check and increment/decrements in a single statement of an iterative loop, while loop could be used. In while loop statement, only condition statement is present.
Syntax:
#include<stdio.h>
int main()
 {   
       int i = 0, flag = 0;
       int a[10] = { 0, 1, 4, 6, 89, 54, 78, 25, 635, 500 };
       //This loop is repeated until the condition is false.
       while (flag == 0) 
       { 
             if (a[i] == 54) 
              {
                    //as element is found, flag = 1,the loop terminates
                    flag = 1;
              }
            else {
                     i++;
                    }
        }// End of while
        printf ("Element found at %d th location", i);
        return 0;
}// End of main
Output:
Element found at 5th location
Explanation:
Here flag is initialized to zero. 'while' loop repeats until the value of flag is zero, increments i by 1. 'if' condition checks whether number 54 is found. If found, value of flag is set to 1 and 'while' loop terminates.     

Thursday, 20 June 2013