I have a question regarding a "counter" inside a nested "for loop", and use this counter to count how many times the loop has been executed. Below is an example code:
-----------------------------------------
for ( x = 0; x < 10; x++)
{
for (y = 0; y < 5; y++)
{
counter1++;
}
couter2++;
}
cout << couter1 << " " << counter2;
-----------------------------------------
Accourding to my understanding, the total amount executed for the nested "for loop" should be 50 times (10 * 5 = 10 outer loops * 5 nested loops( for each outer loops) ), but how come the output for "counter1" is 98?...did I miss place this counter?
for (x = 0; x < 10; x++)
{
for (y = 0; y < 5; y++)
{
counter1++;
}
counter2++;
}
cout << counter1 << "," << counter2;
return 0;
}
------------------------------------------------
output: 98,10
ummm........when I change the test expressions "x < 10 and y < 5" to "x < 5 and y < 2" the counter1 outputs 58 lol.......I got no idea what the error is.
hmmm, I've modified the program based on your insight, and counter1 turned out to be 50:
int x, y, counter1 = 0, counter2;
for (x = 0; x < 10; x++)
{
for (y = 0; y < 5; y++)
{
counter1 += 1;
}
counter2++;
}
cout << counter1;
but, i'm still curious as to why using "counter2++" worked while "counter1++"
isn't outputting the correct number.
And, when I initialize "counter1 = 0"; using "counter1++" worked correctly and outputted 50 xD.....I guess it's the initialization part.......bah I'm so lost here lol.
Two people were running the red light. One reached the other side, second got hit by a car. Why?
Using uninitialized variable is undefined behavior. You just happened to get correct result. On your next run, or when you change your program, or when you reboot your PC, or when you upgrade your compiler, or in any of thousand of possibilities you can get wrong result.
You should never use uninitialized variables.
Also it is a good idea to declare loop counters inside loop itself:
1 2 3 4 5 6 7 8
int counter_inner = 0;
int counter_outer = 0;
for(int x = 0; x < 10; ++x) {
for(int y = 0; y < 5; ++y)
++counter_inner;
++counter_outer;
}
std::cout << counter_inner << "; " << counter_outer << '\n';