Public Group

# [C++] for loop acting strange

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

## 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 on other sites
Once e reaches zero, your loops stop displaying anything. What rows did you expect?

##### Share on other sites
Think carefully: after the e loop runs once, the d loop should repeat (with d=5 instead of d=6). What is the value of e when this happens?

##### Share on other sites
Oh, yeah, of course... thanks :)

##### Share on other sites
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 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

##### 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 on other sites
Quote:
 Original post by NotAYakkOr, more cleanly:*** Source Snippet Removed ***Declare variables near initializaton, and as close to use as possible.

My work here is done [grin]

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

(You must login to your GameDev.net account.)

• 10
• 11
• 13
• 9
• 9
• ### Forum Statistics

• Total Topics
634082
• Total Posts
3015400
×