Nesting of loops

http://install4install.com

Loops can be nested if required.Nesting means to have one or more loops inside the main loop.

Syntax of nested for loops

for(initialization;condition;iteration)

{

for(……)

{

for(…)

{…

}

…….

}

}

Syntax of nested while loops

while(condition)

{

…..

while(condition)

{

……..

}

….

}

Syntax of nested do-while loop

do

{

statements;

do

{

statements;

}

while(condition);

}

while(condition);

Example 1

Say we want to print a pattern like

#
# #
# # #
# # # #
# # # # #

Program 1

 

#include <stdio.h>

int main() 
{
int i,j;
for(i=0;i<5;i++)
{
	for(j=0;j<=i;j++)
	{
		printf("*");
	}
	printf("\n");
}
	return 0;
}

Run

Illustration 

The working of Program 1 is explained in Fig 1.

 

Screen Shot 2014-07-08 at 6.06.39 PM

Fig 1 : Working of Program 1

 

Example 2

Say we want to print table of numbers from 5 t0 10.If we need to print a table of single number then single loop can be used.In order to print table of different numbers in a single go,we need nested loop.

 

Program 2

#include <stdio.h>

int main()
{
	
	int i,j;
	int res;
	
	for(i=5;i<=10;i++)
	{
		printf("\n");
		for(j=1;j<=10;j++)
		{
			res = i*j;
			printf("%d * %d = %d",i,j,res);
			printf("\n");
		
		}
		
	}
	return 0;
}

Run



Short URL: http://tinyit.cc/00849b
Author: Cusp2207 on July 9, 2014
Category: Computer Science
Tags:

Leave a Reply

Last articles