I know for while loops you type
while(argument){
do whatever
}
you have to use the brackets to enclose just like I used in my code right here.
It is a simple while loop that is a countdown.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int n =10;
while(n>0){
cout << n << ", ";
--n;
}
cout << "Liftoff!\n";
}
My question is that when I take the brackets away from my while loop, my code will still execute but it just prints out the number "10" repeatedly. I was just wondering why it does this and why the compiler does not throw out an error when I leave off the brackets after the "while()". thanks for the help!
I tried setting it up as "n--;" without the brackets and the same exact thing happened; it outputted 10 continuously. And it also worked like it is suppose to when the brackets are there. Does it not matter whether the "--" are after or before the "n"?
That means only the statement that directly follows is part of the loop, so if you take away the { } from your code only line 10 will be part of the loop.
A list of statements enclosed inside { } is a compound-statement, i.e. a statement that contain multiple statements and that's what you'll have to use if you want multiple statements to be part of the loop.
Thank you, your explanation makes a lot of sense! I am new to C++ and I don't quite have a firm grasp on the loops yet and their syntax. But I am learning. I am about to take my intro to C++ course this summer so You will probably see a lot of posts from me asking many questions! Thanks again!
and also no one had explained why "n--" and "--n" are the same thing?
and also no one had explained why "n--" and "--n" are the same thing?
It has to do with context. In any expression, like:
1 2 3
int n = 10;
a = --n;
b = n--;
--n will reduce n in 1 before assigning it o a, thus a will be 9
whereas
n-- will reduce n in 1 after assigning it to b, thus, b will be 9
after that, n will be 8