TMF 1414
Introduction to Programming
Lecture 04: Control Structure
Relational operators
Selection Structure Component in a program code
if
if-else
Repetition Control Structure
for
Content while
do while
Switch Multiple Selection Statement
Break, continue, goto statement
Logical Operation
For example:
Consider int main() {
this int age;
printf(“What is your age?”);
program scanf(“%d”, &age);
printf(“your age is %d”, age);
return 0;
}
Consider this…
What if your program have more than two ways to perform?
For example:
If age 18 and above is adult, while younger than 18 is teenager.
From the program in previous slide, how can you code your program to perform in
a way to determine you as adult or minor based on your input?
In order to the change the code, you need to know the appropriate operational
operator to use
Relational Relational operators are used to
compare values of two expressions.
operators
Relational operators are binary
operators because they require two
operands to operate.
An expression which contains the
relational operators is called relational
expression.
If the relation is true then the result
of the relational expression is 1, if the
relation is false then the result of the
relational expression is 0.
Operator Description Example Result
> Greater than 1>2 0
>= Greater than or 3 >= 2 1
equal to
Relational
< Smaller than 10 < 5 0 operators
<= Smaller than 6 <= 7 1
or equal to
== equal to 98==98 1
!= not equal to 10 != 9 1
The if Selection Statement
Also known as single if statement
if (condition){
statement(s)
}
For example, you can use the earlier example.
If age 18 and above is adult, while younger than 18 is teenager
The pseudocode statement
If age is equal to 18 and above,
you are adult will be printed
if age is less than 18,
you are teenager is printed
The if Selection Statement
(Cont.)
The preceding pseudocode If statement may be written in C as
if ( age >= 18 ) {
printf( “You are adult\n" );
}
if (age < 18){
printf(“You are teenager\n”);
}
Notice that the C code corresponds closely to the pseudocode
The if Selection Statement
(Cont.)
The flowchart on the next page illustrates the single-selection if statement.
This flowchart contains what is perhaps the most important flowcharting
symbol—the diamond symbol, also called the decision symbol, which
indicates that a decision is to be made.
The decision symbol contains an expression, such as a condition, that can
be either true or false.
The if Selection Statement (Cont.)
yes
if Display
age >= 18 You are adult
no
yes
if Display
age < 18 You are teenager
no
The if…else Selection
Statement
The if…else selection statement allows you to specify that different actions are
to be performed when the condition is true and when it’s false.
For example, the pseudocode statement
If age is greater than or equal to 18
Print “You are adult”
else
Print “You are teenager”
In either case, after printing occurs, the next pseudocode statement in sequence
is “performed.” The body of the else is also indented.
The if…else Selection
Statement (Cont.)
The preceding pseudocode If…else statement may be written in C as
if ( age >= 18 ) {
printf( “You are adult\n" );
}
else {
printf( “You are teenager\n" );
}
The flowchart on the next page illustrates the flow of control in the if…else
statement.
Once again, besides small circles and arrows, the only symbols in the
flowchart are rectangles for actions and a diamond for a decision.
The if…else Selection Statement (Cont.)
yes
if Display
age >= 18 You are adult
no
Display
You are teenager
The if…else Selection
Statement (Cont.)
C provides the conditional operator (?:) which is closely related to the if…
else statement.
Syntax :
condition ? result1 : result2
If the condition is true, result1 is returned else result2 is returned.
Example:
( age >= 18 ) ? printf(“Adult \n”) : printf(“Teenager \n”);
nested if…else Selection
Statement
Nested if...else Statements
test for multiple cases by placing if…else statements inside if…else
statements.
For example, the following statements will
print Kids if age is less than 12
print Teenager if age is less than 18
print Adult if age is less than 60
print Senior if age is greater or equal to 60
nested if…else Selection
Statement
Pseudocode
If age is less than 12
Print “Kids”
else
If age is less than 18
Print “Teenager”
else
If age is less than 60
Print “Adult”
else
Print “Senior”
nested if…else Selection
Statement
This pseudocode may be written in C as
if (age < 12)
printf("Kids\n");
else {
if (age<18)
printf("Teenager\n");
else {
if (age<60)
printf("Adult\n");
else
printf("Senior");
}
}
if…else if…else Selection
Statement
This nested if…else can be simplified using if..else if..else
if (age < 12)
printf("Kids\n");
else if(age<18)
printf("Teenager\n");
else if (age<60)
printf("Adult\n");
else
printf("Senior");
The if…else Selection
Statement (Cont.)
As far as the C compiler is concerned, both forms are equivalent.
The latter form is popular because it avoids the deep indentation of the code
to the right.
The if selection statement expects only one statement in its body—if you
have only one statement in the if’s body, you do not need the enclose it in
braces.
To include several statements in the body of an if, you must enclose the set
of statements in braces ({ and }).
A set of statements contained within a pair of braces is called a compound
statement or a block.
The if…else Selection
Statement
The following example includes a compound statement in the else part of an
if…else statement.
if ( age >= 18 ) {
printf( “Adult\n" );
}
else {
printf( “Teenager\n" );
printf( “Soon, you will be an adult\n");
}
If only one statement per condition the {} can be omitted
More than 1 statements, the {} is needed. If missing {},like else condition,
the printf(“Teenager\n”); is considered the only statement belongs to else
condition.
Repetition Essentials
A loop is a group of instructions the computer executes repeatedly while some
loop-continuation condition remains true.
We’ve discussed two means of repetition:
Counter-controlled repetition
Sentinel-controlled repetition
Counter-controlled repetition is sometimes called definite repetition because
we know in advance exactly how many times the loop will be executed.
Sentinel-controlled repetition is sometimes called indefinite repetition because
it’s not known in advance how many times the loop will be executed.
Repetition Essentials
There are three repetition/looping structures that can be used for counter-controlled repetition
for loop
while loop
do-while loop
For loop and while loop are pre-test condition looping
Condition must be true in order to proceed the looping block { }
If condition false, the looping block is not executed
Do-while loop is a post-test condition looping
The looping block { } will execute at least once
The looping will continue if the condition is true. If false, the loop is terminated immediately
For sentinel repetition, for loop structure is not suitable. You can apply while loop or do-while loop to
implement sentinel repetition
Repetition Essentials
PRE-TEST LOOPING POST-TEST LOOPING
for(initial_counter; condition; update_counter){ initial_counter;
statement; do{
… statement;
} ….
update_counter;
initial_counter; }while(condition);
while(condition){
statement;
…
update_counter;
}
Counter-Controlled
Repetition Example
Write a program using loop controlled to display “This is my first program” for
10 times.
TIPS: For the solution, you may use any three types of loop to solve the above
problem.
For loop
solution
For loop header
components
General flowchart of for loop
Assign 1 to
counter
counter yes Display
<=10 This is my first counter++
program
no
Examples using the for loop
The following examples show methods of varying the control variable in a for statement.
Vary the control variable from 1 to 100 in increments of 1.
for ( i = 1; i <= 100; ++ i )
Vary the control variable from 100 to 1 in increments of -1 (decrements of 1).
for ( i = 100; i >= 1; --i )
Vary the control variable from 7 to 77 in steps of 7.
for ( i = 7; i <= 77; i += 7 )
Vary the control variable from 20 to 2 in steps of -2.
for ( i = 20; i >= 2; i -= 2 )
Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17.
for ( j = 2; j <= 17; j += 3 )
Vary the control variable over the following sequence of values: 44, 33, 22, 11, 0.
for ( j = 44; j >= 0; j -= 11 )
While loop
solution
General flowchart of while loop
Assign 1 to
counter
while yes Display
counter This is my first counter++
<=10 program
no
Do-while
loop solution
General flowchart of do-while loop
Assign 1 to
counter
yes
Display while
This is my first counter++ counter
program <=10
no
The switch Multiple-Selection
Statement
switch
Useful when a variable or expression is tested for all the values it can assume and different actions are
taken
Format
Series of case labels and an optional default case
switch ( value ){
case ‘a':
actions
case ‘b':
actions
default:
actions
}
break; exits from statement
33
The switch
Multiple-Selection
Statement
Flowchart of the switch
statement
Switch case
examples
The break and continue
Statements
break
Causes immediate exit from a while, for, do…while or switch statement
Program execution continues with the first statement after the structure
Common uses of the break statement
Escape early from a loop
Skip the remainder of a switch statement
36
1 /* Fig. 4.11: fig04_11.c
2 Using the break statement in a for statement */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int x; /* counter */
9
10 /* loop 10 times */
11 for ( x = 1; x <= 10; x++ ) {
12
13 /* if x is 5, terminate loop */
14 if ( x == 5 ) {
15 break; /* break loop only if x is 5 */
16 } /* end if */ break immediately ends for
17 loop
18 printf( "%d ", x ); /* display value of x */
19 } /* end for */
20
21 printf( "\nBroke out of loop at x == %d\n", x );
22
23 return 0; /* indicate program ended successfully */
24
25 } /* end function main */
1 2 3 4
Broke out of loop at x == 5
The break and continue
Statements
continue
The continue statement, when executed in a while, for or do…while
statement, skips the remaining statements in the body of that control statement
and performs the next iteration of the loop.
In while and do…while statements, the loop-continuation test is evaluated
immediately after the continue statement is executed.
In the for statement, the increment expression is executed, then the loop-
continuation test is evaluated.
38
1 /* Fig. 4.12: fig04_12.c
2 Using the continue statement in a for statement */
3 #include <stdio.h>
4
39 5 /* function main begins program execution */
6 int main( void )
7 {
8 int x; /* counter */
9
10 /* loop 10 times */
11 for ( x = 1; x <= 10; x++ ) {
12
13 /* if x is 5, continue with next iteration of loop */
14 if ( x == 5 ) {
15 continue; /* skip remaining code in loop body */
16 } /* end if */
continue skips to end of for
17
loop and performs next iteration
18 printf( "%d ", x ); /* display value of x */
19 } /* end for */
20
21 printf( "\nUsed continue to skip printing the value 5\n" );
22
23 return 0; /* indicate program ended successfully */
24
25 } /* end function main */
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
goto
statement goto statements is used to transfer
the normal flow of a program to the
specified label in the program.
Logical Operators
C provides logical operators that may be used to form more complex
conditions by combining simple conditions.
The logical operators are && (logical AND), || (logical OR) and ! (logical
NOT also called logical negation).
Logical operator
Logical AND
Returns true if both conditions are
true.
Logical OR
Returns true if either of its
conditions are true.
Logical NOT
Reverses the truth/false of its
condition
unary operator, has one operand
Logical Operators (Cont.)
Summary of Operator
Precedence and Associativity
The operators are shown
from top to bottom in
decreasing order of
precedence.
Confusing Equality (==) and
Assignment (=) Operators
operators == (equality) and = (assignment).
What makes these swaps, so damaging is the fact that they do not ordinarily
cause compilation errors.
Rather, statements with these errors ordinarily compile correctly, allowing
programs to run to completion while likely generating incorrect results
through runtime logic errors.
Confusing Equality (==) and
Assignment (=) Operators (Cont.)
For example, suppose we intend to write
if ( payCode == 4 )
printf( “%s“, "You get a bonus!" );
but we accidentally write
if ( payCode = 4 )
printf( “%s“, "You get a bonus!" );
The first if statement properly awards a bonus to the person whose paycode
is equal to 4.
The second if statement—the one with the error—evaluates the assignment
expression in the if condition.
Confusing Equality (==) and
Assignment (=) Operators (Cont.)
This expression is a simple assignment whose value is the constant 4.
Because any nonzero value is interpreted as “true,” the condition in this if
statement is always true, and not only is the value of payCode inadvertantly
set to 4, but the person always receives a bonus regardless of what the
actual paycode is!
Confusing Equality (==) and
Assignment (=) Operators (Cont.)
Confusing == and = in Standalone Statements
The other side of the coin can be equally unpleasant.
Suppose you want to assign a value to a variable with a simple statement
such as
x = 1;
but instead write
x == 1;
Here, too, this is not a syntax error.
Rather the compiler simply evaluates the conditional expression.
Thank you for
your attention
Any question?