0

I need help understanding the for statements. This segment of code repeats itself as so
1
22
333
4444
However, i need understanding in how it repeats itself. Thanks

#include <stdio.h>

int main ()
{ 
	int i,j;


	for(i=1;i<5;i++)
	{
		for(j=1;j<=i;j++)
	         printf("%d",i);
		 printf("\n");

	}
}
3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by tomato.pgn
0

Inner loop index (j) is just used to print the outer loop index (i) as long as condition in inner loop satisfies.

0

#include <stdio.h>

int main ()
{
int i,j;


for(i=1;i<5;i++)
{
for(j=1;j<=i;j++)
printf("%d",i);
printf("\n");

}
}

The code that u gave works in the following way...-
It is a nested for loop that is a loop within another loop...
So u can picturize this as...

for(i=1;i<5;i++)
	{
		for(j=1;j<=i;j++)
	         {
                   printf("%d",i);
		 }
            printf("\n");
 
	}

the syntax for for loop is(initialization,condition checking,increment)
So in your above example....
First the variable i is initialised to 1....
then in the inner loop the j is initialised to 1 and stopping condition is 1 ,so it runs one time and prints 1. and then it encounters newline
After that i is incremented to 2....
j is again intialised to 1 and runs 2 times and prints 2 2...
And so on...
unti i reaches 5....
Hope i am clear...and you understood this one...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.