For Loop Statement - C Language Tutorial

Description

For loop statement executes a block of statements repeatedly for fixed number of times. It is used when the user knows how many times you want to execute the code.

Syntax

for (intialization expression; test expression; increment expression)
{
//Block of statments to execute
}

Defines three expression

First expression intializes the value of variable only once at the start eg:int i=0;.
Second test expression checks everytime whether the condition is true or not, if true it will enter into block of statements else it will end the loop and controls transfers to the following statement. eg: i<10;
And last increment expression is always executed at the end of loop, which increments the value of the variable. eg: i++;

Source code

  1. //Using for statement to print two's multiplicaton table
  2. #include <stdio.h>
  3. #include <conio.h>
  4. void main()
  5. {
  6. int i,j;
  7. clrscr();
  8. for(i=1;i<=10;i++)
  9. {
  10. j=2*i;
  11. printf("2 x %d = %d\n", i,j);
  12. }
  13. getch();
  14. }

Program working steps

  • First 4 lines in the above program are common in c program containing comments, preprocessor directives and void main() function.
  • Declaration of variables i & j and then clearing of the screen.
  • As we want the program to print two's multiplication table, we need to keep i variable value incrementing and j variable value stable. So by using for statement its very easy to do this thing.
  • In for loop statement first expression intializes the value of i to 1, in second expression it checks the condition whether i values is less than or equal to 10. And third expression increments the value of i by 1.
  • First expression is intialized only once at the start, second expression is checked after every loop. If it satisfies then it enters to the loop and executes two statements written on the line no. 10 & 11. Else it breaks the loop. And third increment expression i++ is always executed at the end of loop
  • So till i=10 the for loop statement will be executed, which is going to give our required result of two's multiplication table.
  • getch() function takes the single input character from the keyboard and that character is not display on the console screen.




Thank you for sharing Your Knowledge with others who need It.-Team LetML

Post a Comment

Copyright © LetML. Blogger Templates Designed by OddThemes