Nested Loop question

This was a problem on a test for an intro to programming class. Here is my solution.


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
28
29
30
//Title: test5
//Author: Macon Leighton
//Date: 09 October 2012

#include <iostream>
#include <cmath>
using namespace std;
int main (void)

// Using 2 NESTED loops, develop a program that gives the following output:
//	2
//	4    4
//	6    6     6
//	8    8     8     8
//	10   10    10    10    10	

{

int n = 0;

for (n = 2 ; n <= 10 ; n=n++)
	{
		for (n = 2 ; n <= n+2 ; n = n+2)
		{
		cout << n << endl;
		}
	cout << endl;
}
return 1;
}


Which works fine and passed the test. Problem is, I'm not really sure why it worked. I was expecting gibberish that I would debug, but hey, a win is a win, right?

So, what's the question? I guess it's "Why does this loop produce the desired pyramid?" I can't seem to follow the order of operations in my head.

This is also my first forum post. Please let me know if there is a better way.

Thanks!
Err... it doesn't. That code does not work at all. It will infinitely loop, spitting out ever larger numbers.

Each of your loops has a problem. On line 21:
 
for (n = 2 ; n <= 10 ; n=n++)


That n=n++ is very very very bad. It results in undefined behavior. You must never modify a variable more than once in the same sequence. ++ already increments n, so there's no need to reassign it

 
for (n = 2 ; n <= 10 ; n++)  // <- better 



Your other loop is also messed up:

 
for (n = 2 ; n <= n+2 ; n = n+2)


Think about that condition for a second: n <= n+2. When will that ever be false? If n=4, then you're comparing 4<=6 (true). Or if n=10, you're comparing 10<=12 (also true). Bottom line is it will always* be true, so this loop is infinite.

* Actually this isn't actually correct... it will just loop for a very very long time, until 'n' wraps past the boundaries of an int.


Also, you should not be using the same loop counter (n) for both loops. Changes made to 'n' in the inner loop will affect the outer loop as well, since they're both using the same variable.
Indeed, n <= n+2 will loop forever, which is one reason I was confused when it compiled and ran fine on my console.

I appreciate the help on the finer details. Perhaps asking a different question will make this more clear.

What if instead of incrementing the value of an integer, we wanted to display symbols? Maybe
$
$$
$$$
$$$$

?
Indeed, n <= n+2 will loop forever, which is one reason I was confused when it compiled and ran fine on my console.


It really couldn't have. You must be recalling incorrectly.

What if instead of incrementing the value of an integer, we wanted to display symbols?


It's the same concept. You have a loop for each row (outer loop), and a loop for each column (inner loop).

The trick is that the column loop will need to reference the row number so that each column is drawn differently.
ok, thanks!
Topic archived. No new replies allowed.