Nested For Loops

How do you format this as a nested for loop?

5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
Can you at least give us an attempt yourself?
int main( void )
{
for( int i=2; i >= 1; i++ )
{
for( int j=4; j >=1; j++ )
{
cout << i+1; <<<<<< having trouble

cout << endl;
}

return 1;
}
For starters, each of your loops will only run once, because the initial values of the loop variables (i and j) already trigger their respective end-loop conditions.

Edit: My apologies - that's what I get for posting before my first coffee of the day. As IdeasMan says below, your loops will run infinitely, because the initial values of the loop variables (i and j) mean that the loop conditions are always true.

You need to think logically about what you want your loops to do.
Last edited on
Please always use code tags, use the <> button on the right.

The loops will run infinitely, because the end conditions are always true.

Here is the idiom for doing something 5 times:

1
2
3
4
for (int a = 0  ;a < 5; a++)  {
//your code here
}


The loop ends when a<5 becomes false.

Edit: You can count backwards, by using the decrement operator like this: a--

Hope this helps

Edit main should return 0 if all is OK.
Last edited on
Thank you guys for the help so far.
Each time I run this code I get a blank output that is about 5 lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main( void )
{ 
  for( int i=1; i <= 5; i++ )
  {
    for( int j=5; j <= 1 ; j-- )
    {
      cout << i*j; 
    }
    
	cout << endl;
  }

return 0;
}
You need to read up again on for loops, and how a for statement works. You need to think about what your inner for statement is actually doing.
Last edited on
There are many ways to get this output with nested loops.
For example

1
2
3
4
5
6
7
8
for ( int i = 0; i < 5; i++ )
{
   for ( int j = 5 - i; 0 < j; j-- )
   {
      std::cout << j;
   }
   std::cout << std::endl;
}
1
2
3
4
5
6
7
8
for (int i=0;i<5;i++)
	{
		for (int j=5;j>i;j--)
		{
				cout<<j-i<<" ";
		}
		cout<<endl;
	}
Thank you all this was very helpful!
Topic archived. No new replies allowed.