Jun 25, 2014

C Programming #21: Loop - for

This section will explain the "for loop". "for loop" has a syntax that imbibes all the 4 parts of loop discussed in article.

Syntax of for loop:

for(initialize_counter; condition; change_condition) {
    statement; // body of the loop
}


Code flow will be as follows:
  1. Expression "initialize_counter" is evaluated first.
  2. "condition" expression is evaluated next, if the condition is true then statement is executed.
  3. After statement evaluation "change_condition" is evaluated and it continues back to step 1. (till condition becomes false.)

Program that prints number 1 to 10 using for loop


#include <stdio.h>

int main()
{
   int counter;

   printf("Start\n");
   for(counter = 1; counter <= 10; counter++) {
       printf("%d ", counter);
   }
   printf("\nEnd\n");
   return 0;
}

output of above program is


Start
1 2 3 4 5 6 7 8 9 10 
End

Program that prints multiplication table using for loop


#include <stdio.h>

int main()
{
   int num = 8;
   int counter;

   for(counter = 1; counter <= 10; counter++) {
       printf("%d x %d = %d\n", num, counter, num * counter);
   }

   return 0;
}

output of above program is


8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80

Note that in above two programs expressions in for loop is the same, while only the body of for loop is different. "for loop" is typically used when the number of times to be looped is already know.

Links

Quiz - Not Yet written !!
Next Article - C Programming #22: Loop - while
Previous Article - C Programming #20: Loop - Introduction
All Articles - C Programming

No comments :

Post a Comment