For Loop Statement
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.
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++;
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.
In for loop you can have multiple intializaton and increment expressions separated by commas but you can't have more than one test expression eg:
for(i=0,j=0; i<10; i++,j++)