1. CHAPTER 5: Decision Making and
Looping
CSEB113 PRINCIPLES of PROGRAMMING
CSEB134 PROGRAMMING I
by
Badariah Solemon
BS (Sept 2012)
1
2. Topics
1. Decision making using:
â
â
â
â
â
â
Simple if selection
Simple ifâŚelse selection and using ?: operator
Handling multiple conditions
Nested ifâŚelse selection
ifâŚelse if selection
switch selection
2. Looping:
â
â
â
â
Design: Counter-controlled vs Sentinel-controlled
Using while loop
Using doâŚwhile loop
Using for loop
3. Data validation in selection and repetition structures
4. Combinations of control structures
5. Using continue and break statements
BS (Sept 2012)
2
4. Intro to Decision Making
⢠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
⢠In this problem, we have identified two conditions/
constraints:
1.
2.
The quantity purchased must be more than zero
The cost per Kg apples must be more than zero
⢠Because of those conditions, before the C program calculates
the total cost of apples purchased, we must make it DECIDE
that both conditions have been met.
⢠We can get our C programs to make decisions of this sort
using Selection Structure
BS (Sept 2012)
4
5. What is Selection Structure?
⢠Take actions depending on the outcome of a condition. A condition is a
logical expression that is either True or False.
⢠General forms of selection structure (SYNTAX):
if (condition)
then-statement;
else
else-statement;
if (condition)
3
then-statement;
else if (condition)
elseif-statement;
âŚ
else
else-statement;
if(condition)
then-statement;
1
2
(condition)? then-statement : else-statement;
switch (ControlVariable)
{
case constant 1:
statement;
break;
case constant-n:
statement;
break;
default:
statement;
}
BS (Sept 2012)
4
5
7. if Selection
⢠Is used when a statement or group of statements is to be executed when
the logical expression of the condition is TRUE.
an expression that can return true or false
⢠Syntax:
if (condition)
single then-statement;
No semicolon at the end of the
if statement.
â The expression of the condition must be specified using Relational and
Equality operators as follows:
Type
Operator
Meaning
Example
expression
Result if x=5 and
y=4
Relational
>
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 is less than or equal to y
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
Equality
BS (Sept 2012)
7
8. Example â Relational Operator
⢠Case Apples: the algorithm is refined by making the
Begin
program decide that the following condition
is met:
â
Prompt and get
QtyApple
The quantity purchased must be more than zero
Prompt and get
Cost
Begin
Prompt and get QtyApple
Prompt and get Cost
if QtyApple > 0
Compute: TotalCost = Cost * QtyApple
End if
Display TotalCost
End
F
QtyApple > 0?
T
Compute:
TotalCost = Cost * QtyApple
Print TotalCost
End
BS (Sept 2012)
8
9. Example â Relational Operator
⢠Based on the refined algorithm, the C program is as follows:
BS (Sept 2012)
9
10. if with Compound Statements
⢠In the example that we have seen so far, there is only one
statement to be executed after the if statement.
⢠To execute more than one statement after the condition is
satisfied, we have to put curly braces { } around those
statements.
⢠Syntax:
if (condition)
{
multiple then-statements;
}
⢠Example:
F
QtyApple > 0?
T
Print message
if (QtyApple > 0)
{
printf(âCalculating the total costnâ);
Total = Cost * QtyApple;
}
BS (Sept 2012)
Compute:
TotalCost = Cost * QtyApple
10
11. Example â Equality Operator
⢠This example demonstrates the use of equality operators ==
and !=
⢠Note that == is different that =. Why?
Prompt and get
status
F
status == 1?
T
Print âKidsâ
F
status != 0?
T
Print âAdultsâ
BS (Sept 2012)
11
12. Exercise
What is the output of this program?
If values entered are:
a)
b)
c)
the
789 and 12
44 and 44
3 and 9901
BS (Sept 2012)
12
14. 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.
⢠Syntax:
No semicolon at
if (condition)
else
the end of the if
and else.
Single then-statement ;
Single else-statement ;
⢠Example:
F
if (QtyApple > 0)
Total = Cost * QtyApple;
else
printf(âInvalid quantity!nâ);
BS (Sept 2012)
Print message
QtyApple > 0?
T
Compute:
TotalCost = Cost
* QtyApple
14
15. ifâŚelse with Compound Statements
⢠put curly braces { } around a group of statements
⢠Syntax:
Example: if (QtyApple > 0)
{
if (condition)
{
Multiple then-statements ;
}
else
{
Multiple else-statements;
}
printf(âCalculating the total costnâ);
Total = Cost * QtyApple;
}
else
{
printf(âInvalid quantity!nâ);
Total = 0.0;
}
F
QtyApple > 0?
Print message â
invalid quantity
Total = 0.0
T
Print message
Compute:
TotalCost = Cost * QtyApple
BS (Sept 2012)
15
16. Other Variations of Syntax of ifâŚelse
1. With one then-statement and multiple elsestatements. Syntax:
if (condition)
else
{
F
QtyApple > 0?
Print message â
invalid quantity
}
T
Single then-statement;
Multiple else-statements;
Compute:
TotalCost = Cost * QtyApple
Example:
Total = 0.0
if (QtyApple > 0)
Total = Cost * QtyApple;
else
{
printf(âInvalid quantity!nâ);
Total = 0.0;
flag = âIâ;
}
flag = âIâ
BS (Sept 2012)
16
17. Other Variations of Syntax of ifâŚelse
2. With multiple then-statements and one elsestatement.
Syntax: if (condition)
{
}
else
Multiple then-statements;
single else-statement ;
F
Example:
if (QtyApple > 0)
{
Total = Cost * QtyApple;
flag = âVâ;
}
else
printf(âInvalid quantity!nâ);
QtyApple > 0?
T
Compute:
TotalCost = Cost * QtyApple
Print message â
invalid quantity
flag = âIâ
BS (Sept 2012)
17
18. Effect of Omitting { }
⢠This what might happens if the { } are omitted
int score;
printf(âEnter the score: â);
scanf(â%dâ,&score);
Enter the score: 75
You have done very well
Iâll give you a present
Sorry no present for you
Go and study more
if (score >= 60)
{
printf(âYou have done very wellnâ);
printf(âIâll give you a presentnâ);
}
else
printf(âYou have failed the coursenâ);
printf(âSorry no present for younâ);
printf(âGo and study moreâ);
BS (Sept 2012)
18
19. Test your skill
⢠What happens if we omit the { }?
int score;
printf(âEnter the score: â);
scanf(â%dâ,&score);
if (score >= 60)
printf(âYou have done very wellnâ);
printf(âIâll give you a presentnâ);
else
{
printf(âYou have failed the coursenâ);
printf(âSorry no present for younâ);
printf(âGo and study moreâ);
}
BS (Sept 2012)
19
20. Conditional Operator ( ? : )
⢠Used to simplify an ifâŚelse statement.
⢠Syntax:
( condition) ? Single then-statement : single else-statement;
⢠The statement above is equivalent to:
if (condition)
single then-statement;
else
single else-statement;
BS (Sept 2012)
20
21. Example
⢠ifâŚelse statement:
if (total > 60)
printf("Passed!!n");
else
printf("Failed!!n");
F
Print âFailedâ
total > 0?
T
Print âPassedâ
⢠Conditional statement:
printf("%s!!n", total > 60? "Passed" : "Failed");
OR
total > 60 ? printf("Passedn") : printf(âFailedn");
BS (Sept 2012)
21
24. Multiple Conditions â Apples Case
⢠Re-call that in the Apples Case problem, we have identified
two conditions/ constraints:
1.
2.
The quantity purchased must be more than zero
The cost per Kg apples must be more than zero
⢠So far, we have handled only the first condition in these
statements: if (QtyApple > 0)
Total = Cost * QtyApple;
⢠We can get our program to check multiple conditions in one
logical expression, using logical operator &&. Example:
if (QtyApple > 0 && Cost > 0)
Total = Cost * QtyApple;
BS (Sept 2012)
24
25. Logical Operators
⢠To connect two conditions:
Operator
Read as
Evaluation
Example
&&
AND
All the conditions must
be true for the whole
expression to be true.
if (x == 10 && y == 9)
The truth of one
condition is enough to
make the whole
expression true
if (x == 10 || y == 9)
Reverse the meaning
of a condition
if (!(points > 90))
||
!
OR
NOT
The if condition is true only when value
x is 10, AND value of y is 9.
The if condition is true when either one
of x OR y has the right value.
Means if points NOT bigger than 90
BS (Sept 2012)
25
26. Results of a Logical Expression
⢠Each logical expression with multiple conditions has either
True or False value, depending of the value of each condition
in it.
⢠This table lists possible result of a logical expression. Symbols
A and B indicate conditions.
A
B
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
27. Example
#include<stdio.h>
void main ( )
{
int x=5, y=0;;
printf(âx=%d
y=%dnnâ, x,y);
if (x>0 && y>=0)
printf(âx greater than zero and â
ây greater than or equal to zeronnâ);
if (x==0 || y==0)
printf(âx and y equal to zeronnâ);
if (!(x==y))
printf(âx is not equal to ynâ);
}
x=5
y=0
x greater than zero and y greater than or equal to zero
x and y equal to zero
X is not equal to y
BS (Sept 2012)
27
28. 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);
if (gender == âfâ && age > 20)
{
car_loan = 200000.00;
printf(âYour car loan is %.2fnâ, loan);
printf(âWell done.nâ);
}
}
BS (Sept 2012)
28
29. Evaluating Multiple Operators in a Logical Expression
⢠The C rules for evaluating logical expression with multiple mix
of operators are parentheses rule, precedence rule and
associativity rule.
⢠For a complete list, refer to Appendix C (Hanly &Koffman)
Precedence
Operation
Highest (evaluated first)
<
Lowest (evaluated last)
Associativity
[ ]( )
!
> <=
== !=
&&
||
?:
L
L
L
L
L
L
R
BS (Sept 2012)
>=
29
30. Example
Single variable â returns
True or False based
on its value
-0 : False
- 1(non-zero): True
#include<stdio.h>
void main ( )
{
int x=8, b=-3, c=0, x;
if(a) printf(âa=%d,
if(b) printf(âb=%d,
!a=%dnâ, a, !a);
!b=%dnâ, a, !a);
if(c) printf(âNever gets printednâ);
else printf(âc=%d, !c=%dnâ, c, !c);
a=8 !a=0
b=-3 !a=0
c=0 !c=1
Answer is FALSE
x=1 !x=0
if (a>b && B>c || a==b) printf(âAnswer is TRUEnâ);
else printf(âAnswer is FALSEnâ);
logical expression â
returns True or False
x = a>b || b>c && a==b;
printf(âx=%d,
!x=%dnâ, x, !x);
}
BS (Sept 2012)
and the result can be
assigned to an integer
variable
30
32. What is Nested if..else?
⢠if and ifâŚelse contained in another ifâŚelse selection.
⢠However, as ifâŚelse statements become nested, programs
become harder to understand.
â To improve readability, indent each pair of ifâŚelse statement
⢠Example syntax (*numbers of âifâs and the numbers of âelseâs are not necessarily equal):
if (outer-condition)
{
âŚ
if (inner1-condition)
{ inner1 -then-statement; }
else
{ inner1-else-statement n; }
}
else
{
âŚ
if (inner2-condition)
{ inner 2-then-statement; }
else
{ inner2-else-statement n; }
}
//if outer is True, execute this block
//if inner1 is True, execute this block
//if inner1 is False, execute this block
//if outer is False, execute this block
//if inner2 is True, execute this block
//if inner2 is False, execute this block
BS (Sept 2012)
32
33. Example
#include<stdio.h>
void main ( )
{
int day, time;
printf(âEnter day and time: â);
scanf(â%d %dâ, &day, &time);
Enter day and time: 3 1000
if (day>0 && day<=6)
Relax
{
if (time<=900) printf(ânSleepnâ);
else
{
if (time <=1900) printf(ânWorknâ);
else printf(ânRelaxnâ);
}
}
else
{
if (time<=1100) printf(ânSleepnâ);
else printf(ânHave funnâ);
}
Draw a flowchart
for this program
}
BS (Sept 2012)
33
35. What is ifâŚelse if selection?
â˘
â˘
if (score >= 90)
printf(âAnâ);
One type of nested selection structure
If any one of the condition is already
satisfied, the other conditions will be
ignored completely.
F
F
F
F
Print
âFâ
score>=80?
score>=70?
score>=60?
T
score>=90?
T
else if (score >= 80)
printf(âBnâ);
T
Print
âAâ
T
Print
âBâ
else if (score >= 70)
printf(âCnâ);
else if (score >= 60)
printf(âDnâ);
else
printf(âFnâ);
Print
âCâ
Print
âDâ
BS (Sept 2012)
35
36. Re-writing ifâŚelse if
⢠if..else if statements can be re-written to multiple single
if statements. But this applies to condition that uses equality
operator only. Example:
âŚ
if (number == 1)
printf(âOnenâ);
else if (number == 2)
printf(âTwonâ);
else if (number == 3)
printf(âThreenâ);
else
printf(âOthersnâ);
âŚ
if (number == 1)
printf(âOnenâ);
if (number == 2)
printf(âTwonâ);
if (number == 3)
printf(âThreenâ);
if (number < 1 && number > 3)
printf(âOthersnâ);
Enter the score: 2
Two
Enter the score: 2
Two
BS (Sept 2012)
36
37. Test your skill
⢠What are the outputs of these programs segments? If value of
score entered is 85
if (score >= 90)
printf(âAnâ);
else if (score >= 80)
printf(âBnâ);
else if (score >= 70)
printf(âCnâ);
else if (score >= 60)
printf(âDnâ);
else
printf(âFnâ);
if (score >= 90)
printf(âAnâ);
if (score >= 80)
printf(âBnâ);
if (score >= 70)
printf(âCnâ);
if (score >= 60)
printf(âDnâ);
if (score < 60)
printf(âFnâ);
⢠Whatâs the effect of re-writing the above if..else if
statements to multiple if statements?
BS (Sept 2012)
37
38. 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:
Ritcher scale number (n)
n < 5.0
5.0 <= n < 5.5
5.5 <= n < 6.5
6.5 <= n < 7.5
n >= 7.5
Effect
Little or no damage
Some damage
Serious damage: walls may crack or
fall
Disaster: house or building may
collapse
Catastrophe: most buildings
destroyed
BS (Sept 2012)
38
40. switch Statement
⢠A switch statement is used to choose one choice
from multiple cases and one default case.
⢠Syntax:
switch (ControlVariable)
{
case constant 1: statement;
break;
case constant-n: statement;
break;
default: statement;
}
The break statement is needed so
that once a case has been executed,
it will skip all the other cases and go
outside the switch statement.
The default clause is executed if
the cases are not met.
BS (Sept 2012)
40
41. Rules for switch Statement
1. The value for âcaseâ must be integer or character only.
â Examples:
switch (number)
{
case 1 :
num += 2;
break;
}
if (number==1)
num += 2;
switch (color)
{
case âRâ :
colorstr = ârâ;
break;
}
The value for
each case is
followed by
colon (:).
if (color==âRâ)
colorstr = ârâ;
2. The value checked in each âcaseâ must be constant only
and not values in range. case 1 :
case >= 1 :
â
BS (Sept 2012)
X
41
42. 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 graden");
}
num==1?
num==2?
T
T
T
Print
âBad (D)â
Print
âGood (C)â
Print
âExcellent (A)â
}
Enter number: 3
Excellent (A)
BS (Sept 2012)
42
43. Omitting break Statement
#include <stdio.h>
void main()
{
int majorCode;
If the break statement is omitted, the
execution will be carried out to the next
alternatives until the next break statement is
found.
printf("Enter your majoring code: ");
scanf("%d", &majorCode);
switch(majorCode)
{
case 1 :
case 3 :
case 5 : printf(ânScience Studentnâ);
break;
case 2 :
case 4 : printf(ânArt Studentnâ);
} /* end_switch */
Enter your majoring code: 3
}
Science Student
BS (Sept 2012)
43
44. 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 gradenâ);
}
BS (Sept 2012)
⢠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 gradenâ);
44
45. 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
47. 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
⢠Before this, weâve learned to get our program to make decisions using
Selection Structure.
⢠With the program, when a cashier keys in number of kilogram of apples
purchased and the cost per Kg of apples the computer will output the
total cost of apples purchased for one customer. However, to calculate the
total cost for 100 customers, the cashier would need to execute this
program 100 times!
⢠So, the methods by which it is possible to repeat processing without
executing the program or writing the same statements over and over is
called Looping or Iteration using Repetition Structure.
BS (Sept 2012)
47
48. What is Repetition Structure?
⢠Used to repeat a block of statements a number of
times (loop) until a certain condition is met without
having to write the same statements multiple times.
⢠Two design of loops:
⢠To execute a number of
instructions from the
program for a finite, predetermined number of
time
⢠Loop depends of
arithmetic or conditional
expression.
Counter-controlled
⢠To execute a number of
instructions from the
program indifinitely until
the user tells it to stop or
a special condition is met
⢠Loop depends on
a sentinel value.
BS (Sept 2012)
Sentinel-controlled
48
49. Types of Looping
1
while
2
doâŚwhile
3
for
while (condition)
LoopBody-statement;
NO semicolon (;)
do
LoopBody-statement;
while (condition);
for (InitializationExp; Condition; UpdateExp)
LoopBody-statement;
Exp = Expression
BS (Sept 2012)
49
51. while Statement
⢠Syntax:
an expression that can return true or false
while (condition)
single LoopBody-statement;
while (condition)
{
multiple loopBody-statements;
}
⢠Enclose a group of loop body statements within the braces
{}
⢠As long as the condition is met (returns true), the statement
inside the while loop will always get executed.
⢠When the condition is no longer met (returns false), the
program will continue on with the next instruction (the one
after the while loop).
BS (Sept 2012)
51
52. 1. Counter-controlled while Loop
⢠Used to execute a number of instructions from the program for a
finite, pre-determined number of time
⢠Loop depends of arithmetic or conditional expression.
total is the loop controlvariable
Total = 1
Total = 2
Total = 3
In this case, this loop will keep on
looping until the counter total
variable is 5. Once value of total
is 6, the loop will terminate
...
int total = 1;
while (total <= 3)
{
printf(âTotal = %dnâ, total);
total++;
}
x++;
...
BS (Sept 2012)
F
x++
total=1
total <= 3?
T
Print value
of total
total++
52
54. Example 2
⢠You may allow the user to set the number of
iteration as shown in example below :
Begin
#include<stdio.h>
void main (void)
{
int counter=1, n=0;
printf(âNumber of iteration?: â);
scanf(â%dâ, &n);
while(counter <= n)
{
printf("Hello Worldn");
counter++;
}
counter=1, n=0
Prompt and
get n
F
}
// 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
55. Exercise
1. For the following code fragment:
sum =0;
count = 2;
while (count <= 5)
{
sum = sum + count;
count = count + 3;
}
â How many times will the while loop body be executed?
â What will be the end values computed for the variables sum
and count?
2. Write a program that reads 3 integer numbers and
prints the sum of the numbers. Repeat the reading and
printing processes 10 times using while loop.
BS (Sept 2012)
55
56. 2. Sentinel-Controlled while Loop
⢠Counter control loop is used when we know beforehand how
many iteration that the loop should execute.
⢠There will be cases where we (as the programmer) do not
know how many times the loop should be executed, because
the decision is up to the users.
⢠In this case, to terminate the loop, we need to use âsentinel
controlled loopâ method
⢠In order to exit from the loop, the user must enter a unique
data value, called a sentinel value.
⢠The sentinel value must be a value that could not normally
occur as data.
BS (Sept 2012)
56
57. 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
F
Get a value
Value != sentinel
value?
T
Process value
Get next
value
⢠Consider this problem:
â Write a program that reads several integer numbers from the user and
prints the sum of the numbers. The program stops reading numbers
from the users when they enter ZERO.
BS (Sept 2012)
57
58. Example
Prompt and
get num
⢠The sentinel value in this case is ZERO
F
#include <stdio.h>
void main(void)
{
int num, sum = 0;
sum += num
Print value
of sum
Prompt and
get num
printf(âEnter a number [zero to end]: â);
scanf(â%dâ,&num);
while (num != 0)
{
sum += num;
printf(âEnter a number [zero to end]: â);
scanf(â%dâ,&num);
Enter a
}
Enter a
Enter a
printf(âSum = %dnâ, sum);
Sentinel value ZERO will
terminate the loop
number
number
number
Enter a number
Sum = 7
}
BS (Sept 2012)
T
num != 0?
[zero
[zero
[zero
[zero
to
to
to
to
end]:
end]:
end]:
end]:
3
-6
10
0
58
59. Example
#include <stdio.h>
Sentinel value -99 will terminate
main ()
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?
T
count++
sum += score
Prompt and
get score
59
60. 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
2. Write a program that computes and displays the sum of a
collection of Celsius temperatures entered until a sentinel
value of -275 is entered.
BS (Sept 2012)
60
62. 1. Counter-controlled do/while Loop
⢠Syntax:
NO semicolon
do
single LoopBody-statement;
while (condition);
do
{
multiple LoopBody-statements;
} while (condition);
Semicolon here is a MUST
⢠the LoopBody-statement inside it will be executed once no
matter what.
⢠Then only the condition will be checked to decide whether
the loop should be executed again or just continue with the
rest of the program.
BS (Sept 2012)
62
63. Example
#include<stdio.h>
main ( )
{
printf(âHello Worldnâ);
printf(âHello Worldnâ);
printf(âHello Worldnâ);
printf(âHello Worldnâ);
printf(âHello Worldnâ);
}
Hello
Hello
Hello
Hello
Hello
World
World
World
World
World
Begin
#include<stdio.h>
main ()
{
int num = 1;
num=1
Print âHello
Worldâ
do
{
printf("Hello Worldn");
num++;
} while(num <=5);
num++
F
num <= 5?
T
}
End
BS (Sept 2012)
63
64. Example 2
⢠You may allow the user to set the number of
iteration as shown in example below :
Begin
#include<stdio.h>
void main (void)
{
int counter=1, n=0;
printf(âNumber of iteration?: â);
scanf(â%dâ, &n);
num=1
Prompt and
get n
do {
printf("Hello Worldn");
counter++;
} while(counter <= n);
Print âHello
Worldâ
}
// in this example the output varies
depending on the value of n entered
by the user
counter++
F
counter <= n?
T
End
BS (Sept 2012)
64
65. while Loop vs do..while Loop
int total = 10;
int total = 10;
while (total < 10)
{
printf(âTotal = %dnâ, total);
total++;
}
do
{
printf(âTotal = %dnâ, total);
total++;
} while (total < 10);
printf(âByeâ);
printf(âByeâ);
total=10
while loop
total=10
Print value
of total
doâŚwhile
F
Print âByeâ
total < 10?
T
loop
total++
Print value
of total
F
total++
total < 10?
T
Print âByeâ
BS (Sept 2012)
65
66. Exercise
1. For the following code fragment:
sum =0;
count = 2;
do {
sum = sum + count;
count = count + 3;
} while (count <= 5);
â How many times will the doâŚwhile loop body be executed?
â What will be the end values computed for the variables sum
and count?
2.
Re-write the program that reads 3 integer numbers and prints the sum of
the numbers, which keeps on repeating the reading and printing
processes 10 times using doâŚwhile loop.
BS (Sept 2012)
66
67. 2. Sentinel-controlled do/while Loop
⢠The algorithm for sentinel-controlled doâŚwhile loop:
Start do
process the value
read a value to the control variable
While value of the control variable is not sentinel value
⢠Example:
int sum=0, score=0, count=0;
Enter score (or -99 to quit): -99
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
68. 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 doâŚwhile
loop to accomplish the task. Sample input/output:
10.0 12.3 5.6 21.3 9.9
Average: 8.6
2. Re-write the program that computes and displays the sum of
a collection of Celsius temperatures entered until a sentinel
value of -275 is entered using a doâŚwhile loop.
BS (Sept 2012)
68
70. for Loop
⢠Syntax:
MUST semicolons
NO semicolon
for (InitializationExp; Condition; UpdateExp)
single LoopBody-statement;
for (InitializationExp; Condition; UpdateExp)
{
multiple LoopBody-statements;
}
InitializationExp : initialize the loop control variable
Condition : determine whether the condition or test expression
returns True or false
UpdateExp : change value of the loop control variable at the end
of each loop
BS (Sept 2012)
70
71. 1. Counter-controlled for Loop
⢠Example:
Control variable
int total;
for (total = 1; total <= 3; total++)
printf(âTotal = %dnâ, total);
Total = 1
Total = 2
Total = 3
total=1
F
total <= 3?
T
Print value
of total
total++
BS (Sept 2012)
71
72. Example 2
⢠You may allow the user to set the number of
iteration as shown in example below :
Begin
#include<stdio.h>
void main (void)
{
int counter=1, n=0;
printf("Number of iteration?: ");
scanf("%d", &n);
for(counter=1; counter<=n; counter+++)
printf("Hello Worldn");
}
counter=1, n=0
Prompt and
get n
F
End
// in this example the output varies
depending on the value of n entered by
the user
BS (Sept 2012)
counter <= n?
T
Print âHello
Worldâ
counter++
72
73. while Loop vs for Loop
int total = 1;
Both produce same output and have similar order of execution!
Because using a for loop is just another way of writing a while loop.
int total;
while (total <= 3)
{
printf(âTotal = %dnâ, total);
total++;
}
printf(âByeâ);
for(total=1; total<=3; total++)
{
printf(âTotal = %dnâ, total);
}
printf(âByeâ);
total=1
F
Print âByeâ
total <= 3?
total=1
T
Print value
of total
F
Print âByeâ
total++
total <= 3?
T
Print value
of total
total++
BS (Sept 2012)
73
74. Differences between while Loops and for Loops
⢠Although the two are similar in their order of execution, they
are different as follows:
Item
for loop
while loop
Initialization
expression
Is one of the loop expressions
Must be given prior to the
loop
Condition (or test
expression )
Is one of the loop expressions
Is one of the loop expressions
Update expression
Is one of the loop expressions
Must be in the loop body
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
75. Omitting for Loop Expressions
⢠It is also possible to omit one or more of the
for loop expressions.
⢠HOW?
1. Assign initial value to control variable
⢠Example:
2.
Place semicolon without the
expression
int num=1;
for (;num<=5;num++)
{
printf("Hello Worldn");
}
BS (Sept 2012)
75
76. 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
78. Intro to Data Validation
⢠Good programmers would ensure that only valid data are
entered and processed by their programs.
⢠Say for example we want to write a program that reads
the score marks from the user, and print its equivalent
grade.
⢠Say that the valid score marks range is between 0 to100.
So, if user keys in value other than 0 to100, the program
should do something such as the following:
â Option 1: Tell the users that they have entered a wrong
input and terminate the program.
â Option 2: Tell the users that they have entered a wrong
input and ask them to reenter the input.
BS (Sept 2012)
78
79. Data Validation: ifâŚelse if
Option 1: Tell the users that they have entered a wrong input
and terminate the program.
printf(âEnter the score: â);
scanf(â%dâ,&score);
if (score >= 90 && score <= 100)
printf(âAnâ);
else if (score >= 80 && score < 90)
printf(âBnâ);
else if (score >= 70 && score < 80)
printf(âCnâ);
else if (score >= 60 && score < 70)
printf(âDnâ);
else if (score >= 0 && score < 60
printf(âFnâ);
else
printf(âError, input should only be between 0 â 100 nâ);
BS (Sept 2012)
79
80. Data Validation: while Loop
Option 2(1): Tell the users that they have entered a wrong
input and ask them to reenter the input using while loop.
printf(âEnter score: â);
scanf(â%dâ, &score);
Sentinel-controlled while loop
with multiple sentinel values in
the range of < zero or > 100
while (score < 0 || score > 100)
{
printf(âSorry, input must be between 0 â 100nâ);
printf(âRe-enter the score: â);
scanf(â%dâ,&score);
}
if (score >= 90 && score <= 100)
printf(âAnâ);
else if (score >= 80 && score < 90)
printf(âBnâ);
else if (score >= 70 && score < 80)
printf(âCnâ);
else if (score >= 60 && score < 70)
printf(âDnâ);
else
printf(âFnâ);
BS (Sept 2012)
80
81. Data Validation: do..while Loop
Option 2(2): Tell the users that they have entered a wrong
input and ask them to reenter the input using doâŚwhile loop.
do{
printf(âEnter score: â);
scanf(â%dâ,&score);
if (score < 0 || score > 100)
printf(âSorry, input must be between 0 â 100nâ);
}while (score < 0 || score > 100);
if (score >= 90 && score <= 100)
Sentinel-controlled
printf(âAnâ);
doâŚwhile loop with
else if (score >= 80 && score < 90)
multiple sentinel values in
printf(âBnâ);
the range of < zero or >
else if (score >= 70 && score < 80)
100
printf(âCnâ);
else if (score >= 60 && score < 70)
printf(âDnâ);
else
printf(âFnâ);
BS (Sept 2012)
81
82. Data Validation: for Loop
Option 2(3): Tell the users that they have entered a wrong
input and ask them to reenter the input using for loop.
printf("Enter the score:");
for ( scanf("%d", &score); score < 0 || score > 100; scanf("%d", &score))
{
printf(âSorry, input must be between 0 â 100nâ);
printf("Enter the score:");
}
if (score >= 90 && score
printf(âAnâ);
else if (score >= 80 &&
printf(âBnâ);
else if (score >= 70 &&
printf(âCnâ);
else if (score >= 60 &&
printf(âDnâ);
else
printf(âFnâ);
<= 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
84. Possible Combinations
⢠Possible combinations are limitless. Four basic forms of
combinations are as follows:
1.
2.
3.
4.
One or more selection structures inside a repetition structure.
One or more repetition structures inside a selection structure.
Nested selection structures â one or more selection structures
inside a selection structure
Nested repetition structures â one or more repetition
structures inside a repetition structure
⢠This course covers the first three forms only and we have seen
examples of nested selection structures before.
BS (Sept 2012)
84
85. 1. Selection Structures inside a Repetition Structure
⢠Example: a simple if..else inside a while loop
x=1
Prompt and
get status
F
Print
âByeâ
x <= 3?
F
T
status == 1?
Print
âAdultsâ
T
Print
âKidsâ
x++
BS (Sept 2012)
85
86. 2. Repetition Structures inside a Selection Structure
⢠Example: a while loop inside a simple if..else
x=1
Prompt and
get status
F
status == 1?
T
Print
âKidsâ
F
x=1
x <= 3?
T
Print
âAdultsâ
x++
Print
âByeâ
BS (Sept 2012)
86
87. Exercise
1. Write C programs that calculate and
display the average of 10 floating point
numbers read from user by implementing while,
doâŚwhile 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, doâŚwhile and for loops to
implement this.
â˘
Implement appropriate data validation
in the programs
BS (Sept 2012)
87
89. The break statement
⢠The continue and break statements are used to
modify the program flow when a selection structure
or a repetition structure is used.
⢠The break statement can be used to forced exit of
selection or terminate repetition structure.
⢠Example:
for (num=1;num<=5;num++)
{
if (num==2)
break;
printf("Hello Worldn");
}
BS (Sept 2012)
When the value of num is
equals to 2, the program
will terminate from the
for loop.
OUTPUT?
89
90. The break statement
⢠You can use the break statement at any time.
⢠This can be very useful if you want to stop running a
loop because a condition has been met other than
the loop end condition.
The while loop will run,
as long i is smaller then
twenty.
But, the while loop must
stop (break) if i equals to
ten
int i;
i = 0;
while ( i < 20 )
{
i++;
if ( i == 10)
break;
}
BS (Sept 2012)
90
91. The continue Statement
⢠Can be used to skip the rest of the loop body
statements and continue with the next repetition of
the loop (start from the top again - the loop variable
must still be incremented).
for (num=1;num<=5;num++)
⢠Example:
{
When the value of num is
equal to 2, the program
will skip the printf
statement and continue
with the for loop.
if (num==2)
continue;
/* end_if */
printf(âNumber %dnâ,num);
} /*end_for */
OUTPUT?
BS (Sept 2012)
91
92. The continue Statement
⢠In a for loop, any modification to the control
variable will be done before the condition is checked.
⢠In a while and doâŚwhile structures, the loop
condition will be checked as soon as the continue
statement is encountered to determine whether the
loop will be continued .
int i=0;
⢠Example:
In the example above, the
printf function is never
called because of the
continue statement.
while ( i < 20 )
{
i++;
continue;
printf("Nothing to seen");
}
BS (Sept 2012)
92
93. Summary
1.
2.
3.
We can get our C programs to make decisions using Selection
Structure including if, ifâŚelse, ?: operator, ifâŚelse if
and switch.
Also we can get our programs to repeat (loop) processing without
writing the same statements over and over using Repetition
Structure including while loop, doâŚwhile loop, for loop
All the while, doâŚwhile , and for loops can be
implemented as counter-controlled loop or sentinel-controlled
loop.
â When number of iteration is known, use counter-controlled
loop
â When decision to proceed with iteration depends on a value
or a range of values, use sentinel-controlled loop
BS (Sept 2012)
93
94. 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