• Advertisement
Sign in to follow this  

A little confused with nested for loops

This topic is 1653 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello. Kind of new to gamedev.net and to programming in general. Hopefully this is the right place to post.

 

I finished this code below and got it to work. The first nested for loop outputs + signs on each line. 1 on the first line, all the way to 10 on the 10th line.

 

The second nested for loop does the same just reverse.

 

My question is, why doesn't the second nested for loop terminate when j is no longer >= i? 

#include <iostream>
 
using namespace std;
 
int main()
{
    for (int i = 1; i <= 10; ++i)
    {
        for (int j = 1; j <= i; ++j)
        {
            cout << "+";
        }
        cout << endl;
    }
    cout << endl;
 
    for (int i = 1; i <= 10; ++i)
    {
        for (int j = 10; j >= i; --j)
        {
            cout << "+";
        }
        cout << endl;
    }
}

Share this post


Link to post
Share on other sites
Advertisement

My question is, why doesn't the second nested for loop terminate when j is no longer >= i? 

But it does terminate when j is no longer >= i... Can you clarify your question?

Share this post


Link to post
Share on other sites

 

My question is, why doesn't the second nested for loop terminate when j is no longer >= i? 

But it does terminate when j is not longer >= i... Can you clarify your question?

 

 

^^ What he said.

 

Try doing

 

cout << "(" << i << ", " << j << ").";

 

instead of cout << "+";

 

And you will be able to see the values of i and j on the screen each iteration.

Share this post


Link to post
Share on other sites

Oh wow, I get it now. It's hard to explain out loud how I was thinking of it before. It was just weird for me I guess. 

 

Thank both of you very much.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement