CodesandTutorials
Home   Programming   Hardware   Networking
 
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.  

C Categories

For Loop Statement

« Previous Point - Else If Statement Next Point - While Loop Statement »

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

  • //Using for statement to print two's multiplicaton table
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • 	int i,j;
  • 	clrscr();
  • 	for(i=1;i<=10;i++)
  • 	{
  • 		j=2*i;
  • 		printf("2 x %d = %d\n", i,j);
  • 	}
  • 	getch();
  • }

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.

« Previous Point - Else If Statement Next Point - While Loop Statement »

Tip Box

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++)


Advertisement

Rate Website
   

 


Terms of Use | Privacy Policy | Contact Us
CodesandTutorials © 2014 All Rights Reserved