Hi, I have a problem using "for" statements. I had to write the same program using the "while" statement a while ago and it works fine, but when I tried to do it using for, the number infinitely decreases.
Here is my statement using the while statement which works the way I want it to
1 2 3 4 5 6 7 8 9 10
#include <iostream>
int main()
{
int val = 10;
while (val>=0) {
std::cout << val << std::endl;
--val;
}
return 0;
}
Here is my for statement which infinitely decreases instead of the number going from 10 to 0.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main()
{
int val = 10;
for (int val = 0; val <=10; --val)
std:: cout << val << std::endl;
--val;
return 0;
}
I tried to fix it, but when I do it's like it doesn't read my code at all and tells me to press a key to exit.
You want it to go from 10 to 0 but look at your function.
You set it equal to 0 then decrease by 1 while it is less than or equal to 10.
Maybe you meant to set it equal to 0 and then decrease while it is >= 0?
1 2 3
for( initial_value; condition; modification );
^^^
for( int i = 10; i > -1; --i ) std::cout << i << std::endl;
Also you have a pointless --val on line 8. The for loop is going to automatically do that sinceyou have it doing that on line 6 and anyways you don't have braces so only line 7 are included in the for loop. if you did put braces that would be the same as
1 2 3 4 5 6
while( val > -1 )
{
--val;
std::cout << val << std::endl;
--val; //not neccessay
}