Facebook

for loop

Loops are control structures that are used to execute a code several times.There may be situation when we need to print series from 1-100 or we need to print our name 1000 times on screen.It will be inappropriate to use 100 or thousand  times printf for this scenario.Loops can be used to efficiently perform the task as many times as required.There are 3 types of loops used in C language.They are:

  • for loop
  • while
  • do-while

for loop

for loop is a control structure which has  initialization statement,condition  and iteration statement.

Syntax

for(initialization,condition,iteration)

{

body_of_loop

}

  • In initialization,variable is initialized i.e variable is assigned some value.Declaration can also be done in this step.
  • If the condition is true,body of the loop is executed otherwise flow of control jumps to next lines of code after the ending of loop.After this,control jumps back to increment statement.
  • The incrementation/ decrementation  is done and condition is checked again.If it is true then control goes to body of loop and executes it.
  • The same process happens again and again until the condition becomes false.
  • When the condition becomes false control exits the for loop.

Example 1

Say we need to print  numbers from 0 to 100.For loop can be used to fulfill this task.

Program 1

#include <stdio.h>

int main() 
{
int i;
printf("Numbers are ");
for(i=0;i<=100;i++)
{
	printf("%d\t",i);
}
	return 0;
}

Run

 

Illustration

The working of program 1 is explained in Fig 1.

Screen Shot 2014-07-02 at 4.25.26 PM
Fig 1 : Working of Program 1

 

Example 2

Say we want to print a table of a user entered number.

 

Program 2

#include <stdio.h>

int main() 
{
int n;
int i;
int t;
//printf("Enter the number");
scanf("%d",&n);
printf("The table of %d is:\n ",n);
for(i=1;i<=10;i++)
{
	t=n*i;
	printf("%d * %d = %d\n",n,i,t);
}

	return 0;
}

Run

 

Example 3

Say we want to print even numbers and odd numbers from 0-100  separately .

 

Program 3

 

#include <stdio.h>

int main() 
{
	int i,j;
	printf("The even numbers are:\n");
	for(i=0;i<=100;i=i+2)
	{
		printf("%d\t",i);
	}
	printf("\nThe odd numbers are:\n");
	for(j=1;j<100;j=j+2)
	{
		printf("%d\t",j);
	}
	return 0;
}

Run

 

Example  4

Say we want to print series like  64,32,16,8,4,2,1

Program 4

#include <stdio.h>

int main() 
{
	int i;
	for(i=64;i>0;i=i/2)
	{
		printf("%d\t",i);
	}

	return 0;
}

Run

 

Rate this post

Comments

So empty here ... leave a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sidebar