OK, let's discuss the bracket.
A while loop in general has this structure:
1 2
|
while (condition)
statement;
|
I think you what this means. First the
condition
is tested. If it is
true
, the
statement
is executed. After that, the condition is tested again and so on.
Notice that there is just a
single statement controlled by the loop. Now it is a general principle in C++, that anywhere that you can use a single statement, you can replace that by a
compound statement
.
What is a compound statement? It consists of zero or more statements enclosed in braces. Some examples. First a single statement:
|
cout << "a = " << a << endl;
|
Now a compound statement:
1 2 3
|
{
cout << "a = " << a << endl;
}
|
Another:
|
{ } // empty compound statement
|
and one more, a complete example this time:
1 2 3 4 5 6 7 8
|
int a = 5;
while (a--)
{
cout << "a = " << a;
cout << " squared = " << a * a << endl;
}
|
Output:
a = 4 squared = 16
a = 3 squared = 9
a = 2 squared = 4
a = 1 squared = 1
a = 0 squared = 0
|
But - I'm just reciting the contents of a textbook. Rather than continuing to do that, I would strongly suggest that you read through the tutorial pages on this site:
http://www.cplusplus.com/doc/tutorial/
And even better, get yourself a C++ textbook as well.