Control Structure in C
Control Structure in C
Control Structure in C
Flow of Control
• Unless specified otherwise, the order of statement
execution through a function is linear: one statement after
another in sequence
– if statement
– if-else statement
– switch statement
Logic of an if statement
condition
evaluated
true
false
statement
The if Statement
• The if statement has the following syntax:
The condition must be a
boolean expression. It must
evaluate to either true or
if is a C
false.
reserved word
if ( condition )
statement;
condition
evaluated
true false
statement1 statement2
The if-else Statement
• An else clause can be added to an if
statement to make an if-else statement
if ( condition )
statement1;
else
statement2;
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
• Note the difference between the equality operator (==) and the
assignment operator (=)
Boolean Expressions in C
• C does not have a boolean data type.
5-21
Comparison of Loop Choices (2/2)
Kind When to Use C Structure
Input validation Repeated interactive input do-while
loop of a value until a desired
value is entered.
General Repeated processing of while, for
conditional data until a desired
loop condition is met.
5-22
The while Statement in C
• The syntax of while statement in C:
while (loop repetition condition)
condition
statement
• Loop repetition condition is the condition
which controls the loop.
• The statement is repeated as long as the loop
repetition condition is true.
true
• A loop is called an infinite loop if the loop
repetition condition is always true.
5-23
An Example of a while Loop
Loop repetition condition
Statement
Statement
5-25
The for Statement in C
• The syntax of for statement in C:
for (initialization expression;
expression
loop repetition condition;
condition
update expression)
expression
statement
• The initialization expression set the initial value of the
loop control variable.
• The loop repetition condition test the value of the
loop control variable.
• The update expression update the loop control
variable. 5-26
An Example of the for Loop
Initialization Expression
Update Expression
5-31