Read this chapter, which explains while loops. This is in contrast to how a do-while loop works, which we will discuss later. In a do-while loop, the body of the loop is executed at least one time, whereas in a while loop, the loop may never execute if the loop condition is false.
5. Syntax of the while statement
Answer:
- How many times was the condition true? 3
- How many times did the block statement following the
while
execute? 3
Syntax of the while
statement
while
statement
Here is the syntax for the while
statement:
while ( condition )
statement
Varieties of while Statements | |
---|---|
while ( condition ) | while ( condition ) |
Notes:
- The condition is a Boolean expression: something that evaluates to true or false.
- The condition can be complicated, using many relational operators and logical operators.
- The statement is a single statement. However it can be (and usually is) a block statement containing several other statements.
- The statement is sometimes called the loop body.
Since the statement can be a single statement or a block statement, a while
statement looks like either choice in the table. Almost always, though, a while
statement is used with a block.
The style of indenting used here leads to fewer errors than alternative styles. The statements controlled by the while
are indented. The braces of the block are aligned with each other and with the while
and each is put on its own line.
Question 5:
Is the condition always surrounded by parentheses?