Thracing the nested loops with inner if and inner loop wit inner if

Hi! I'm having a problem reading through an outerloop nested with inner if and inner loop and nested with inner if again in the inner loop. Please help me, how to read this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
#include <string>

using namespace std;
int main(){
    cout << "Enter #: ";
int enteredNum =0;
cin >> enteredNum ;
int temp = 0;

for(int ctr = 1 ; ctr <= ((enteredNum * 2) - 1); ctr++)
{
if(ctr > enteredNum)
{
temp++;
}
for(int ctr2 = 1; ctr2 <= (ctr- (temp * 2)); ctr2++ )
{
cout << ctr2;
}
cout << "\n";
}

    return 0;

}
It would be nice, if you did add systematic indentation to your code. It really helps reading.

What does happen here?
1
2
3
4
5
6
7
8
for (int ctr = 1 ; ctr <= ((enteredNum * 2) - 1); ctr++)
{
  if (ctr > enteredNum)
  {
    temp++;
  }
  cout << "\n";
}

The ctr increases monotonically on every iteration from 1 to (enteredNum * 2) - 1.
We do know that 1 <= enteredNum+1 <= enteredNum*2-1. (Unless the enteredNum is too small.)

We could thus split that range into two: 1 to enteredNum and enteredNum+1 to enteredNum*2-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for (int ctr = 1 ; ctr <= enteredNum; ctr++)
{
  if (ctr > enteredNum)
  {
    temp++;
  }
  cout << "\n";
}

for (int ctr = enteredNum+1 ; ctr <= ((enteredNum * 2) - 1); ctr++)
{
  if (ctr > enteredNum)
  {
    temp++;
  }
  cout << "\n";
}

What can you now say about the two if-constructs?
Topic archived. No new replies allowed.