Thursday, 28 October 2010

for loop


for Loop Syntax


for(initialization statement; test expression; update statement) {
       code/s to be executed;
}


How for loop works in C programming?

The initialization statement is executed only once at the beginning of the for loop. Then the test expression is checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.

for loop example
Write a program to find the sum of first n natural numbers where n is entered by user. Note: 1,2,3... are called natural numbers.

#include <stdio.h>
int main(){
    int n, count, sum=0;
    printf("Enter the value of n.\n");
    scanf("%d",&n);
    for(count=1;count<=n;++count)  //for loop terminates if count>n
    {
        sum+=count;    /* this statement is equivalent to sum=sum+count */
    }
    printf("Sum=%d",sum);
    return 0;
}

Output
Enter the value of n.
19
Sum=190
In this program, the user is asked to enter the value of n. Suppose you entered 19 then,  count is initialized to 1 at first. Then, the test expression in the for loop,i.e.,  (count<= n) becomes true. So, the code in the body of for loop is executed which makes sum to 1. Then, the expression ++count is executed and again the test expression is checked, which becomes true. Again, the body of for loop is executed which makes sum to 3 and this process continues. When count is 20, the test condition becomes false and the for loop is terminated.

You may like the following posts:

Algorithm to find the sum of first n natural numbers
Flowchart  to find the sum of first n natural numbers
Interview Questions on for loops
C for Loop Examples



No comments:

Post a Comment