Professional Documents
Culture Documents
Chapter 5 - Decision Making and Looping
Chapter 5 - Decision Making and Looping
and Looping
CSEB113 PRINCIPLES of
PROGRAMMING CSEB134
PROGRAMMING I
by
Badariah Solemon
BS (Sept 2012)
Topics
1. Decision making using:
Simple if selection
Simple ifelse selection and using ?: operator
Handling multiple conditions
Nested ifelse selection
ifelse if selection
switch selection
2. Looping:
Topic 1
DECISION MAKING
BS (Sept 2012)
BS (Sept 2012)
Topic 1-1
SIMPLE if SELECTION
BS (Sept 2012)
if Selection
Syntax: if (condition)
single thenstatement;
Equality
expressio
n
and y=4
>
x is greater than y
x > y
5 > 4 is TRUE
<
x is less than y
x < y
5 < 4 is FALSE
>=
x is greater than or
equal to y
x >= y
5 >= 4 is TRUE
<=
x <= y
5 <= 4 is
FALSE
==
x is equal to y
x == y
5 == 4 is
FALSE
!=
x is not equal to y
x != y
5 != 4 is TRUE
BS (Sept 2012)
Example Relational
Operator
Case Apples: the algorithm is refined by making
the
program decide that the followingBegin
condition
is met:
Begin
Prompt and get QtyApple
Prompt and get Cost
if QtyApple > 0
Compute: TotalCost = Cost * QtyApple
End if
Display TotalCost
End
QtyApple > 0?
Compute:
Print TotalCost
End
BS (Sept 2012)
Example Relational
Operator
Based on the refined algorithm, the C program is
as follows:
BS (Sept 2012)
if with Compound
Statements
In the example that we have seen so far, there is
multiple thenstatements;
}
QtyApple > 0?
Print message
(QtyApple > 0)
ifExample:
{
Compute:
}
BS (Sept 2012)
10
status == 1?
Print Kids
status != 0?
Print Adults
BS (Sept 2012)
11
Exercise
What is the output of this program?
the If values entered are:
a)789 and 12
b)44 and 44
c)3 and 9901
BS (Sept 2012)
12
Topic 1-2
SIMPLE ifelse SELECTION
BS (Sept 2012)
13
Simple if..else
Is used when a statement or group of
statements is to be executed when the
logical expression of the condition is
FALSE.
No semicolon
if (condition)
at the end of
Single then Syntax:
the if and
else
statement ;
else.
Single else-statement
;
if (QtyApple
> 0)
Example:
Print message
QtyApple > 0?
Compute:
TotalCost = Cost
* QtyApple
printf(Invalid quantity!\n);
BS (Sept 2012)
14
Multiple then-statements ;
}
else
{
printf(Invalid quantity!\n);
Total = 0.0;
Multiple else-statements;
}
F
QtyApple > 0?
Print message
invalid quantity
Total = 0.0
Print message
Compute:
BS (Sept 2012)
15
QtyApple > 0?
Print message
invalid quantity
Single then-statement;
Multiple elsestatements;
Compute:
Total = 0.0
if (QtyApple > 0)
Total = Cost *
else
{
printf(Invalid
Total = 0.0;
flag = I;
}
flag = I
BS (Sept 2012)
Example:
QtyApple;
quantity!\n);
16
Multiple then-statements;
single else-statement ;
Example:
if (QtyApple > 0)
{
Total = Cost * QtyApple;
flag = V;
}
else
printf(Invalid quantity!\n);
QtyApple > 0?
Compute:
Print message
invalid quantity
BS (Sept 2012)
flag = I
17
Effect of Omitting { }
This what might happens if the { }
are omitted
int score;
printf(Enter the score: );
scanf(%d,&score);
BS (Sept 2012)
18
19
Conditional Operator ( ? : )
Used to simplify an ifelse
statement.
Syntax:
( condition) ? Single then-statement : single elsestatement;
The
statement above is equivalent
if (condition)
single thento:statement;
else
single elsestatement;
BS (Sept 2012)
20
Example
ifelse statement:
if (total > 60)
printf("Passed!!\n");
else
printf("Failed!!\n");
Print Failed
total > 0?
Print Passed
Conditional statement:
printf("%s!!\n", total > 60? "Passed" : "Failed");
OR
total > 60 ? printf("Passed\n") : printf(Failed\n");
BS (Sept 2012)
21
Example 2
#include <stdio.h>
void main(void)
{
char grade;
int marks;
printf("Enter marks");
scanf("%d\n", &marks);
grade = (marks > 60)? 'P': 'F';
printf("\nGrade = %c\n", grade);
}
(marks > 60)? printf("%c",'P'): printf("%c",'F');
BS (Sept 2012)
22
Topic 1-3
HANDLING MULTIPLE
CONDITIONS
BS (Sept 2012)
23
BS (Sept 2012)
24
Logical Operators
To connect two conditions:
Operat
or
Read
as
Evaluation
Example
&&
AND
if (x == 10 && y == 9)
if (x == 10 || y == 9)
Reverse the
meaning of a
condition
||
OR
NOT
BS (Sept 2012)
25
Results of a Logical
Expression
Each logical expression with multiple conditions
A &&
B
A || B
!A
!B
True
True
True
True
False
False
True
False
False
True
False
True
False
True
False
True
True
False
False
False
False
False
True
True
BS (Sept 2012)
26
Example
#include<stdio.h>
void main ( )
{
int x=5, y=0;;
printf(x=%d
y=%d\n\n, x,y);
if (!(x==y))
printf(x is not equal to y\n);
x=5
y=0
BS (Sept 2012)
27
Exercise
What is the output of this program?
If input data are:
f 25
f 17
- m 25
- m 17
- F 25
- F 17
- M 25
- M 17
#include<stdio.h>
void main ( )
{
char gender;
int age;
float loan;
printf(Enter your gender (f/F or m/M) and age:);
scanf(%c %d, &gender, &age);
28
Highest (evaluated
first)
<
Lowest (evaluated
last)
Operation
Associativity
[ ]( )
!
>
<=
== !=
&&
||
?:
L
L
L
L
L
L
R
BS (Sept 2012)
>=
29
Example
#include<stdio.h>
void main ( )
{
int x=8, b=-3, c=0, x;
if(a) printf(a=%d,
if(b) printf(b=%d,
if(c)
else
!a=%d\n, a, !a);
!b=%d\n, a, !a);
Single variable
returns True or
False based on its
value
-0 : False
- 1(non-zero): True
a=8 !a=0
b=-3 !a=0
c=0 !c=1
Answer is FALSE
x=1 !x=0
printf(x=%d,
!x=%d\n, x, !x);
BS (Sept 2012)
Topic 1-4
NESTED ifelse SELECTION
BS (Sept 2012)
31
Example
syntax
if (outer-condition)
Example
#include<stdio.h>
void main ( )
{
int day, time;
printf(Enter day and time: );
scanf(%d %d, &day, &time);
BS (Sept 2012)
Draw a flowchart
for this program
33
Topic 1-5
ifelse if SELECTION
BS (Sept 2012)
34
What is ifelse if
selection?
F
F
F
F
Print
F
score>=70?
score>=60?
score>=80?
score>=90?
Print
A
Print
B
printf(D\n);
else
Print
C
printf(F\n);
Print
D
BS (Sept 2012)
35
Re-writing ifelse if
if (number == 1)
printf(One\n);
else if (number == 2)
printf(Two\n);
else if (number == 3)
printf(Three\n);
else
printf(Others\n);
if (number == 1)
printf(One\n);
if (number == 2)
printf(Two\n);
if (number == 3)
printf(Three\n);
if (number < 1 && number > 3)
printf(Others\n);
BS (Sept 2012)
36
37
Exercise
Write a program that prompts the users to
enter the value of Ritcher scale
number (n), and
print its
equivalent effect as a message to the
users based on the following table:
BS (Sept 2012)
38
Topic 1-6
switch SELECTION
BS (Sept 2012)
39
switch Statement
A switch statement is used to choose one
choice from multiple cases and one default
case.
Syntax:
The break statement is
switch
{
case
(ControlVariable)
break;
case constant-n: statement;
break;
default: statement;
BS (Sept 2012)
40
if (number==1)
num += 2;
}
case 1 :
num += 2;
break;
The value
for each
case is
followed
by colon
(:).
if (color==R)
colorstr = r;
1 :
41
Example
The logic of this switch selection is similar to if
else if
#include <stdio.h>
void main()
{
int num;
printf(Enter number:");
scanf("%d", &num);
F
F
F
Print
False grade
num==3?
switch (num)
{
case 1: printf("Bad (D)\n");break;
case 2: printf("Good (C)\n");break;
case 3: printf("Excellent (A)\n");break;
default: printf(False grade\n");
}
}
num==2?
num==1?
T
Print
Bad (D)
Print
Good (C)
Print
Excellent (A)
Enter number: 3
Excellent (A)
BS (Sept 2012)
42
43
Example
char grade;
printf(Enter the grade you scored:);
scanf(%c,&grade);
switch (grade)
{
case a:
case A:
printf(Excellent!!\n);
printf(You brilliant..\n);
break;
case b:
case B:
printf(Job well done!!\n);
printf(You deserve it..\n);
break;
default:
printf(undefined grade\n);
}
Observe the
equivalent logical
expression. What
can you conclude
from these two
program segments?
if (grade == a || grade == A)
{
printf(Excellent!!\n);
printf(You brilliant..\n);
}
else if (grade == b || grade == B)
{
printf(Job well done!!\n);
printf(You deserve it..\n);
}
else
printf(undefined grade\n);
BS (Sept 2012)
44
Exercise
1. Using switch statement, write a program
that reads a positive integer
number
between 1 to 5, and
prints the word equivalent to it.
For example, if the user enters 5, the
program should print the word Five to
the screen.
BS (Sept 2012)
45
Topic 2
LOOPING
BS (Sept 2012)
46
Intro to Looping
Re-call the Apples problem:
Compute and display the total cost of apples given
the number of kilogram (Kg) of apples purchased
and the cost per Kg of apples
47
What is Repetition
Structure?
Used to repeat a block of statements a number of
Types of Looping
1
LoopBody-statement;
dowhile
NO semicolon
do
LoopBody-statement;
while (condition);
for
BS (Sept 2012)
49
Topic 2-1
while LOOP
BS (Sept 2012)
50
while Statement
Syntax:
while (condition)
single LoopBodystatement;
while (condition)
{
multiple loopBodystatements;
}
51
1. Counter-controlled while
Loop
Used to execute a number of instructions from the
program for a finite, pre-determined number of
time
Loop dependstotal
of arithmetic
or conditional
is the loop controlvariable
Total
= 1
expression.
In this case, this loop will keep on
Total = 2
Total = 3
...
int total = 1;
while (total <= 3)
{
printf(Total = %d\n, total);
total++;
}
x++;
...
BS (Sept 2012)
x++
total=1
total <= 3?
T
Print value
of total
total++
52
Example
#include<stdio.h>
main ( )
{
printf(Hello
printf(Hello
printf(Hello
printf(Hello
printf(Hello
}
World\n);
World\n);
World\n);
World\n);
World\n);
Hello
Hello
Hello
Hello
Hello
Begin
#include<stdio.h>
main ()
{
int num = 1;
World
World
World
World
World
num=1
while(num < 6)
{
printf("Hello World\n");
num++;
}
End
num < 6?
T
Print Hello
World
num++
BS (Sept 2012)
53
Example 2
You may allow the user to set the
number of iteration as shown in
example below :
#include<stdio.h>
Begin
counter=1, n=0
Prompt and
get n
}
// in this example the output varies
depending on the value of n entered
by the user
BS (Sept 2012)
End
counter < n?
T
Print Hello
World
counter++
54
Exercise
1. For the following code fragment:
sum =0;
count = 2;
while (count <= 5)
{
sum = sum + count;
count = count + 3;
}
55
2. Sentinel-Controlled while
Loop
Counter control loop is used when we know
56
2. Sentinel-Controlled while
Loop
The algorithm for sentinel-controlled while loop:
Read/assign a value to control variable
While value of the control variable is not
sentinel value
process the value
read the next value
end_while
Get a value
Value != sentinel
value?
Process value
Get next
value
57
Example
Prompt and
get num
sum += num
Print value
of sum
Prompt and
get num
num != 0?
while (num != 0)
{
sum += num;
printf(Enter a number [zero to end]: );
scanf(%d,&num);
Enter a
}
Enter a
Enter a
printf(Sum = %d\n, sum);
Enter a
[zero
[zero
[zero
[zero
to
to
to
to
end]:
end]:
end]:
end]:
3
-6
10
0
Sum = 7
BS (Sept 2012)
58
Example
#include <stdio.h>
Sentinel value -99 will
main ()
terminate the loop
{
int sum=0, score=0, count=0;
printf("Enter first score or (-99 to quit):");
scanf("%d", &score);
while (score != -99)
{
count++;
sum += score;
printf("Enter next score or (-99 to quit):");
scanf("%d", &score);
F
}
printf("Sum of %d scores: %d", count, sum);
Print value of
count and sum
Enter first score (or -99 to quit): 80
Enter next score (or -99 to quit): 77
Enter next score (or -99 to quit): -99
Sum of 2 scores: 157
BS (Sept 2012)
Prompt and
get score
score!= -99?
count++
sum += score
Prompt and
get score
59
Exercise
1. Write a program that calculates and prints the
average of several real numbers.
Assume the last
value read is the
sentinel 9.9. Use a while loop to
accomplish the task. Sample input/ouput:
10.0 12.3 5.6 21.3 9.9
Average: 8.6
BS (Sept 2012)
60
Topic 2-2
dowhile LOOP
BS (Sept 2012)
61
1. Counter-controlled
Loop
Syntax:
do
do/while
NO semicolon
single LoopBody-statement;
while (condition);
do
{
multiple LoopBodystatements;
} while (condition);
62
Example
#include<stdio.h>
main ( )
{
printf(Hello World\n);
printf(Hello World\n);
printf(Hello World\n);
printf(Hello World\n);
printf(Hello World\n);
}
Hello
Hello
Hello
Hello
Hello
World
World
World
World
World
Begin
num=1
#include<stdio.h>
main ()
{
int num = 1;
Print Hello
World
do
{
printf("Hello World\n");
num++;
} while(num <=5);
num++
num <= 5?
End
BS (Sept 2012)
63
Example 2
You may allow the user to set the
number of iteration as shown in
example below :
#include<stdio.h>
Begin
num=1
Prompt and
get n
do {
printf("Hello World\n");
counter++;
} while(counter <= n);
Print Hello
World
}
// in this example the output varies
depending on the value of n entered
by the user
counter++
counter <= n?
End
BS (Sept 2012)
64
Loop
do
{
printf(Bye);
printf(Bye);
Print Bye
total=10
while loop
total=10
Print value
of total
dowhile
loop
total++
Print value
of total
F
total++
Print Bye
BS (Sept 2012)
65
Exercise
1. For the following code fragment:
sum =0;
count = 2;
do {
sum = sum + count;
count = count + 3;
} while (count <= 5);
2.
BS (Sept 2012)
66
2. Sentinel-controlled do/while
Loop
Example:
do
{
Sum of 1 scores: 0
count++;
sum += score;
printf("Enter score or (-99 to quit):");
scanf("%d", &score);
} while (score != -99);
printf("\nSum of %d scores: %d", count, sum);
BS (Sept 2012)
67
Exercise
1. Re-write the program that calculates and prints
the average of several real numbers
after the last
value read is the
sentinel 9.9 by using a dowhile
loop to
accomplish the task. Sample input/output:
10.0 12.3 5.6 21.3 9.9
Average: 8.6
68
Topic 2-3
for LOOP
BS (Sept 2012)
69
for Loop
Syntax:
MUST semicolons
NO semicolon
70
1. Counter-controlled for
Loop
Control variable
Example:
int total;
for (total = 1; total <= 3; total++)
printf(Total = %d\n, total);
Total = 1
Total = 2
Total = 3
total=1
total <= 3?
T
Print value
of total
total++
BS (Sept 2012)
71
Example 2
You may allow the user to set the
number of iteration as shown in
example below :
#include<stdio.h>
Begin
counter=1, n=0
Prompt and
get n
End
counter <= n?
T
Print Hello
World
counter++
72
total=1
Print Bye
total <= 3?
total=1
T
Print value
of total
Print Bye
total++
total <= 3?
T
Print value
of total
total++
BS (Sept 2012)
73
for loop
while loop
Initialization
expression
Condition (or
test
expression )
Update
expression
When number
of iteration is
known
Is very convenient
Is less convenient
When number
of iteration is
unknown
Is less convenient
Is ver y convenient
BS (Sept 2012)
74
int num=1;
for (;num<=5;num++)
{
printf("Hello World\n");
}
BS (Sept 2012)
75
2. Sentinel-controlled for
Loop
Example:
#include <stdio.h>
main ()
{
int sum=0, score;
printf("Enter first score (or -99 to quit):");
for ( scanf("%d", &score); score != -99; scanf("%d", &score))
{
sum += score;
printf("Enter next score (or -99 to quit):");
}
printf("Sum of all scores: %d", sum);
BS (Sept 2012)
76
Topic 3
DATA VALIDATION
BS (Sept 2012)
77
78
BS (Sept 2012)
79
80
Option 2(2):
<= 100)
score < 90)
score < 80)
score < 70)
BS (Sept 2012)
Sentinel-controlled
for loop with
multiple sentinel
values in the range
of < zero or > 100
82
Topic 4
COMBINATIONS OF CONTROL
STRUCTURES
BS (Sept 2012)
83
Possible Combinations
Possible combinations are limitless. Four basic
forms of combinations are as follows:
1. One or more selection structures inside a
repetition structure.
2. One or more repetition structures inside a
selection structure.
3. Nested selection structures one or more
selection structures inside a selection structure
4. Nested repetition structures one or more
repetition structures inside a repetition structure
84
Prompt and
get status
Print
Bye
x <= 3?
status == 1?
Print
Adults
T
Print
Kids
x++
BS (Sept 2012)
85
status == 1?
T
Print
Kids
x=1
x <= 3?
T
Print
Adults
x++
BS (Sept 2012)
Print
Bye
86
Exercise
1. Write C programs that calculate and
display the average of 10 floating point
numbers read from user by implementing
while, dowhile and for loops to accomplish
the task.
2. Write programs that keep printing the multiples
of the integers 2, namely 2, 4, 8, 16, 32, 64 and
128. Your loop should terminate at 128.
Use while, dowhile and for loops to
implement this.
BS (Sept 2012)
87
Topic 5
continue AND break
STATEMENTS
BS (Sept 2012)
88
BS (Sept 2012)
89
BS (Sept 2012)
90
continue;
/* end_if */
printf(Number %d\n,num);
} /*end_for */
OUTPUT?
BS (Sept 2012)
91
printf("Nothing to see\n");
BS (Sept 2012)
92
Summary
1. We can get our C programs to make decisions using
Selection Structure including if, ifelse, ?: operator,
ifelse if and switch.
2. Also we can get our programs to repeat (loop) processing
without writing the same statements over and over using
Repetition Structure including while loop, dowhile loop,
for loop
3. All the while, dowhile , and for loops can be
implemented as counter-controlled loop or sentinelcontrolled loop.
When number of iteration is known, use countercontrolled loop
When decision to proceed with iteration depends on
a value or a range of values, use sentinel-controlled
loop
BS (Sept 2012)
93
Summary
4. The expression of the condition in the selection
and repetition structures must be specified using
Relational operators (such as >, >=, <, <=) and
Equality operators (==, !=) and several
conditions may be combined using Logical
operators (&&, ||, and !).
5. You may combine sequence, selection and
repetition structures in a C program
6. You may use the continue and break
statements to modify the program flow when a
selection structure or a repetition structure is
used.
BS (Sept 2012)
94