for loop

http://install4install.com

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

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

Syntax

for(initialization,condition,iteration)

{

body_of_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

 



Short URL: http://tinyit.cc/24ddd
Author: Cusp2207 on July 3, 2014
Category: Computer Science
Tags:

Leave a Reply

Last articles