• Advertisement
Sign in to follow this  

[C++] for loop acting strange

This topic is 4177 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

Hey! I'm trying to nest some loops but it's not going my way.
a = b = c = d = e = 6;

for (; a > 0; a--) {
	for (; b > 0; b--) {
		for (; c > 0; c--) {
			for (; d > 0; d--) {
				for (; e > 0; e--) {
					cout << "a: " << a << " b: " << b << " c: " << c << " d: " << d << " e: " << e << endl;
				}
			}
		}
	}
}


This prints out: a: 6 b: 6 c: 6 d: 6 e: 6 a: 6 b: 6 c: 6 d: 6 e: 5 a: 6 b: 6 c: 6 d: 6 e: 4 a: 6 b: 6 c: 6 d: 6 e: 3 a: 6 b: 6 c: 6 d: 6 e: 2 a: 6 b: 6 c: 6 d: 6 e: 1 I expected much more rows as you might imagine.

Share this post


Link to post
Share on other sites
Advertisement
Hi!

You are not resetting the variables between looping, i.e.

a = b = c = d = e = 6;

for (; a > 0; a--) {
b=6;
for (; b > 0; b--) {
c=6;
for (; c > 0; c--) {
d=6;
for (; d > 0; d--) {
e=6;
for (; e > 0; e--) {
cout << "a: " << a << " b: " << b << " c: " << c << " d: " << d << " e: " << e << endl;
}
}
}
}
}

Share this post


Link to post
Share on other sites
Or, less perversely:

int a, b, c, d, e;

for (a = 6; a > 0; a--) {
for (b = 6; b > 0; b--) {
for (c = 6; c > 0; c--) {
for (d = 6; d > 0; d--) {
for (e = 6; e > 0; e--) {
cout << "a: " << a << " b: " << b << " c: " << c << " d: " << d << " e: " << e << endl;
}
}
}
}
}

Regards
Admiral

Share this post


Link to post
Share on other sites
Or, more cleanly:

for (int a = 6; a > 0; a--) {
for (int b = 6; b > 0; b--) {
for (int c = 6; c > 0; c--) {
for (int d = 6; d > 0; d--) {
for (int e = 6; e > 0; e--) {
cout << "a: " << a << " b: " << b << " c: " << c << " d: " << d << " e: " << e << endl;
}
}
}
}
}



Declare variables near initializaton, and as close to use as possible.

Share this post


Link to post
Share on other sites
Quote:
Original post by NotAYakk
Or, more cleanly:
*** Source Snippet Removed ***

Declare variables near initializaton, and as close to use as possible.


My work here is done [grin]

Share this post


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

  • Advertisement