chapter 5: decision making and looping cseb113 principles of programming by badariah solemon 1bs...

96
CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1 BS (Sept 2013)

Upload: piers-flynn

Post on 16-Jan-2016

234 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

CHAPTER 5: Decision Making and Looping

CSEB113 PRINCIPLES of PROGRAMMING

byBadariah Solemon

1BS (Sept 2013)

Page 2: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Topics1. Decision making using:

– Simple if selection– Simple if…else selection and?: conditional 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 structures4. Combinations of control structures5. Using continue and break statements

2BS (Sept 2013)

Page 3: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

DECISION MAKING

Topic 1

BS (Sept 2013) 3

Page 4: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Intro to Decision Making • Identify IOFC for the following problem statement:

• Now, add the following three conditions/ constraints:1. The value of height must be more than zero2. The value of width must be more than zero3. The value of length must be more than zero

• Because of those conditions, before the program calculates the swimming pool’s volume, we must make it DECIDE that all conditions have been met.

• We can get our programs to make decisions of this sort using Selection Structure

BS (Sept 2013) 4

A swimming pool is shaped like a big box . Write a program to find the volume of the swimming pool.

Page 5: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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):

BS (Sept 2013) 5

1

2

3 4

Page 6: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

SIMPLE if SELECTION

Topic 1-1

BS (Sept 2013) 6

Page 7: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

if Selection• Is used when a statement or a group of statements is to be executed when

the logical expression of the condition is TRUE.• Syntax:

– The expression of the condition must be specified using Relational and Equality operators as follows:

BS (Sept 2013) 7

if (condition)single then-

statement;

if (condition)single then-

statement;

No semicolon at the end of the if statement.

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

Equality == x is equal to y x == y 5 == 4 is FALSE

!= x is not equal to y x != y 5 != 4 is TRUE

an expression that can return true or false

Page 8: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example – Relational Operator1• Case – Swimming Pool’s Volume: This algorithm is refined by

making the program decide that the following condition is met:1) The value of height must be more than zero

BS (Sept 2013) 8

Begin

SET height=0.0, length=0.0, width=0.0, volume=0.0

INPUT height, length, width

if height > 0

COMPUTE: volume = height * length * width

End if

OUTPUT volume

End

Begin

SET height=0.0, length=0.0, width=0.0, volume=0.0

INPUT height, length, width

if height > 0

COMPUTE: volume = height * length * width

End if

OUTPUT volume

End

INPUT height, length, width

INPUT height, length, width

COMPUTE volume = height * length

* width

COMPUTE volume = height * length

* width

OUTPUT volumeOUTPUT volume

BeginBegin

EndEnd

IFheight > 0?

TF

SET height=0.0, length=0.0,

width=0.0, volume=0.0

SET height=0.0, length=0.0,

width=0.0, volume=0.0

Page 9: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example – Relational Operator2• Based on the refined algorithm, the program is as follows:

BS (Sept 2013) 9

Page 10: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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:

• Example:

BS (Sept 2013) 10

if (height > 0)

{

printf(“Calculating volume\n”);

volume = height * length * width;

}

if (height > 0)

{

printf(“Calculating volume\n”);

volume = height * length * width;

}

COMPUTE volume = height * length

* width

COMPUTE volume = height * length

* width

IFheight > 0?

TF

OUTPUT messageOUTPUT message

if (condition){

multiple then-statements;}

if (condition){

multiple then-statements;}

Page 11: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example – Equality Operator• This example demonstrates the use of equality operators ==

and !=• Note that == is different that =. Why?

BS (Sept 2013) 11

INPUTstatusINPUTstatus

OUTPUT“Mechanical”

OUTPUT“Mechanical”

IFstatus == ‘m’?

TF

OUTPUT “Civil”OUTPUT “Civil”

IFstatus == ‘p’?

TF

char status;

printf(“Enter membership status (m or p):”);scanf(“%c”, &status);

if (status == ‘m’)printf(“Mechanical\n”);

//end-if

if (status == ‘p’)printf(“Civil\n”);

//end-if

Page 12: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your SkillWhat is the output of this program? the If values entered are:a)789 and 12b)44 and 44c)3 and 9901

BS (Sept 2013) 12

Page 13: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

SIMPLE if…else SELECTION

Topic 1-2

BS (Sept 2013) 13

Page 14: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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:

• Example:

BS (Sept 2013) 14

if (condition)Single then-statement ;

elseSingle else-statement ;

if (condition)Single then-statement ;

elseSingle else-statement ;

if (height> 0)

volume = height* length * width;

else

printf(“Invalid value!\n”);

if (height> 0)

volume = height* length * width;

else

printf(“Invalid value!\n”);

COMPUTEvolume = height * length * width

COMPUTEvolume = height * length * width

OUTPUT error message

OUTPUT error message

IFheight > 0?

TF

No semicolon at the end of the if and else.

Page 15: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

if…else with Compound Statements

• put curly braces { } around a group of statements• Syntax: Example:

BS (Sept 2013) 15

if (condition){

Multiple then-statements ;}else{

Multiple else-statements;}

if (condition){

Multiple then-statements ;}else{

Multiple else-statements;}

if (height > 0)

{

printf(“Calculating volume\n”);

volumne = height * length * width;

}

else

{

printf(“Invalid value!\n”);

volume = 0.0;

}

//end-if-else

if (height > 0)

{

printf(“Calculating volume\n”);

volumne = height * length * width;

}

else

{

printf(“Invalid value!\n”);

volume = 0.0;

}

//end-if-else

COMPUTE volume = height * length

* width

COMPUTE volume = height * length

* width

IFheight > 0?

TF

OUTPUT messageOUTPUT message

SETvolume = 0.0

SETvolume = 0.0

OUTPUT error message

OUTPUT error message

Page 16: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Other Variations of Syntax of if…else1

BS (Sept 2013) 16

1. With one then-statement and multiple else-statements. Syntax: if (condition)

Single then-statement;else{

Multiple else-statements;}

if (condition)Single then-statement;

else{

Multiple else-statements;}

if (height > 0)

volume = height * length * width;

else

{

printf(“Invalid value!\n”);

volume = 0.0;

flag = ‘I’;

}

//end-if

if (height > 0)

volume = height * length * width;

else

{

printf(“Invalid value!\n”);

volume = 0.0;

flag = ‘I’;

}

//end-if

COMPUTE volume = height * length

* width

COMPUTE volume = height * length

* width

IFheight > 0?

TF

SETvolume = 0.0

SETvolume = 0.0

OUTPUT errormessage

OUTPUT errormessage

SETflag = ‘I’

SETflag = ‘I’

Example:

Page 17: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Other Variations of Syntax of if…else2

BS (Sept 2013) 17

if (condition){

Multiple then-statements;}else

single else-statement ;

if (condition){

Multiple then-statements;}else

single else-statement ;

2. With multiple then-statements and one else-statement.

Syntax:

if (height > 0)

{

volume = height * length * width;

flag = ‘V’;

}

else

printf(“Invalid value!\n”);

//end-if-else

if (height > 0)

{

volume = height * length * width;

flag = ‘V’;

}

else

printf(“Invalid value!\n”);

//end-if-else

Example:COMPUTE

volume = height * length * width

COMPUTEvolume = height * length

* width

height > 0? TF

OUTPUT error message

OUTPUT error message

SETflag = ‘V’

SETflag = ‘V’

Page 18: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Effect of Omitting { }• This what might happens if the { } are omitted

BS (Sept 2013) 18

int score;

 

printf(“Enter the score: ”);

scanf(“%d”,&score);

if (score >= 60) { printf(“You have done very well\n”);

printf(“I’ll give you a present\n”);}else printf(“You have failed the course\n”); printf(“Sorry no present for you\n”); printf(“Go and study more”);

int score;

 

printf(“Enter the score: ”);

scanf(“%d”,&score);

if (score >= 60) { printf(“You have done very well\n”);

printf(“I’ll give you a present\n”);}else printf(“You have failed the course\n”); printf(“Sorry no present for you\n”); printf(“Go and study more”);

Enter the score: 75You have done very wellI’ll give you a presentSorry no present for youGo and study more

Page 19: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill• What happens if we omit the { }?

BS (Sept 2013) 19

int score;

 

printf(“Enter the score: ”);

scanf(“%d”,&score);

if (score >= 60)

printf(“You have done very well\n”);printf(“I’ll give you a present\n”);

else{ printf(“You have failed the course\n”); printf(“Sorry no present for you\n”); printf(“Go and study more”);}

int score;

 

printf(“Enter the score: ”);

scanf(“%d”,&score);

if (score >= 60)

printf(“You have done very well\n”);printf(“I’ll give you a present\n”);

else{ printf(“You have failed the course\n”); printf(“Sorry no present for you\n”); printf(“Go and study more”);}

Page 20: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Conditional Operator ( ? : )• Used to simplify an if…else statement.• Syntax:

• The statement above is equivalent to:

BS (Sept 2013) 20

( condition) ? Single then-statement : single else-statement;( condition) ? Single then-statement : single else-statement;

if (condition) single then-statement;else

single else-statement;

if (condition) single then-statement;else

single else-statement;

Page 21: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example1

• if…else statement:

• Conditional statement:

BS (Sept 2013) 21

if (total > 60)printf("Passed!!\n");

elseprintf("Failed!!\n");

if (total > 60)printf("Passed!!\n");

elseprintf("Failed!!\n");

printf("%s!!\n", total > 60? "Passed" : "Failed");printf("%s!!\n", total > 60? "Passed" : "Failed");

total > 60 ? printf("Passed\n") : printf(“Failed\n");total > 60 ? printf("Passed\n") : printf(“Failed\n");

OUTPUT “Failed”OUTPUT “Failed”

IFtotal > 0?

TF

OUTPUT “Passed”OUTPUT “Passed”

OR

Page 22: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example2

BS (Sept 2013) 22

#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);

}

#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');(marks > 60)? printf("%c",'P'): printf("%c",'F');

Page 23: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

HANDLING MULTIPLE CONDITIONS

Topic 1-3

BS (Sept 2013) 23

Page 24: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Multiple Conditions – Box’s Volume Case

• Re-call that in the Swimming Pool’s Volume Case problem, we have identified three conditions/ constraints:1. The value of height must be more than zero2. The value of width must be more than zero3. The value of length must be more than zero

• So far, we have handled only the first condition in these

statements:

• We can get our program to check multiple conditions in one logical expression, using logical operator &&. Example:

BS (Sept 2013) 24

if (height > 0)

volume = height * length * width;

if (height > 0)

volume = height * length * width;

if (height > 0 && length > 0 && width > 0)

volume = height * length * width

if (height > 0 && length > 0 && width > 0)

volume = height * length * width

Page 25: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Logical Operators• To connect two conditions:

BS (Sept 2013) 25

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 if condition is true only when value x is 10, AND value of y is 9.

|| OR The truth of one condition is enough to make the whole expression true

if (x == 10 || y == 9)

The if condition is true when either one of x OR y has the right value.

! NOT Reverse the meaning of a condition

if (!(points > 90))

Means if points NOT bigger than 90

Page 26: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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.

BS (Sept 2013) 26

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

Page 27: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example

BS (Sept 2013) 27

#include<stdio.h>void main ( ){

int x=5, y=0;

printf(“x=%d y=%d\n\n”, x,y);

if (x>0 && y>=0)printf(“x greater than zero and ” “y greater than or equal to zero\n\n”);

if (x==0 || y==0)printf(“x and y equal to zero\n\n”);

if (!(x==y))printf(“x is not equal to y\n”);

}

#include<stdio.h>void main ( ){

int x=5, y=0;

printf(“x=%d y=%d\n\n”, x,y);

if (x>0 && y>=0)printf(“x greater than zero and ” “y greater than or equal to zero\n\n”);

if (x==0 || y==0)printf(“x and y equal to zero\n\n”);

if (!(x==y))printf(“x is not equal to y\n”);

}

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

Page 28: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill• What is the output of this program? If input data are:

– f 25 - m 25 - F 25 - M 25 – f 17 - m 17 - F 17 - M 17

BS (Sept 2013) 28

#include<stdio.h>void main ( ){

char gender;int age=0;float loan=0.0;

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 %.2f\n”, loan);printf(“Well done.\n”);

}}

#include<stdio.h>void main ( ){

char gender;int age=0;float loan=0.0;

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 %.2f\n”, loan);printf(“Well done.\n”);

}}

Page 29: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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)

BS (Sept 2013) 29

Precedence Operation Associativity

Highest (evaluated first)

Lowest (evaluated last)

[ ] ( )!

< > <= >=== !=

&&||? :

LLLLLLR

Page 30: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example

BS (Sept 2013) 30

#include<stdio.h>void main ( ){

int a=8, b=-3, c=0, x=0;

if(a) printf(“a=%d, !a=%d\n”, a, !a);if(b) printf(“b=%d, !b=%d\n”, a, !a);

if(c) printf(“Never gets printed\n”);else printf(“c=%d, !c=%d\n”, c, !c);

if (a>b && B>c || a==b) printf(“Answer is TRUE\n”);else printf(“Answer is FALSE\n”);

x = a>b || b>c && a==b;

printf(“x=%d, !x=%d\n”, x, !x);}

#include<stdio.h>void main ( ){

int a=8, b=-3, c=0, x=0;

if(a) printf(“a=%d, !a=%d\n”, a, !a);if(b) printf(“b=%d, !b=%d\n”, a, !a);

if(c) printf(“Never gets printed\n”);else printf(“c=%d, !c=%d\n”, c, !c);

if (a>b && B>c || a==b) printf(“Answer is TRUE\n”);else printf(“Answer is FALSE\n”);

x = a>b || b>c && a==b;

printf(“x=%d, !x=%d\n”, x, !x);}

Single variable – returns True or False based on its value-0 : False- 1(non-zero): True

a=8 !a=0b=-3 !a=0c=0 !c=1Answer is FALSEx=1 !x=0

logical expression – returns True or False

and the result can be assigned to an integer variable

Page 31: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

NESTED if…else SELECTION

Topic 1-4

BS (Sept 2013) 31

Page 32: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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):

BS (Sept 2013) 32

if (outer-condition){ … //if outer is True, execute this block

if (inner1-condition){ inner1 -then-statement; } //if inner1 is True, execute this block

else{ inner1-else-statement n; } //if inner1 is False, execute this block

}else{ … //if outer is False, execute this block

if (inner2-condition){ inner 2-then-statement; } //if inner2 is True, execute this block

else{ inner2-else-statement n; } //if inner2 is False, execute this block

}

if (outer-condition){ … //if outer is True, execute this block

if (inner1-condition){ inner1 -then-statement; } //if inner1 is True, execute this block

else{ inner1-else-statement n; } //if inner1 is False, execute this block

}else{ … //if outer is False, execute this block

if (inner2-condition){ inner 2-then-statement; } //if inner2 is True, execute this block

else{ inner2-else-statement n; } //if inner2 is False, execute this block

}

Page 33: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example

BS (Sept 2013) 33

#include<stdio.h>void main ( ){

int day=0, time=0;

printf(“Enter day and time: ”);scanf(“%d %d”, &day, &time);

if (day>0 && day<=6){ if (time<=900) printf(“\nSleep\n”); else { if (time <=1900) printf(“\nWork\n”); else printf(“\nRelax\n”);

}}else{ if (time<=1100) printf(“\nSleep\n”); else printf(“\nHave fun\n”); }

}

#include<stdio.h>void main ( ){

int day=0, time=0;

printf(“Enter day and time: ”);scanf(“%d %d”, &day, &time);

if (day>0 && day<=6){ if (time<=900) printf(“\nSleep\n”); else { if (time <=1900) printf(“\nWork\n”); else printf(“\nRelax\n”);

}}else{ if (time<=1100) printf(“\nSleep\n”); else printf(“\nHave fun\n”); }

}

Enter day and time: 3 1000

Relax

Draw a flowchart for this program

Page 34: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

if…else if SELECTION

Topic 1-5

BS (Sept 2013) 34

Page 35: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

What is if…else if selection?

BS (Sept 2013) 35

if (score >= 90) printf(“A\n”);

else if (score >= 80) printf(“B\n”);

else if (score >= 70) printf(“C\n”);

else if (score >= 60)

printf(“D\n”);

else

printf(“F\n”);// end-if-else-if

if (score >= 90) printf(“A\n”);

else if (score >= 80) printf(“B\n”);

else if (score >= 70) printf(“C\n”);

else if (score >= 60)

printf(“D\n”);

else

printf(“F\n”);// end-if-else-if

• One type of nested selection structure• If any one of the condition is already

satisfied, the other conditions will be ignored completely.

IFscore>=90?

TF

OUTPUT“A”

OUTPUT“A”

IFscore>=80?

IFscore>=60?

IFscore>=70?

TF

TF

OUTPUT“F”

OUTPUT“F”

OUTPUT“C”

OUTPUT“C”

OUTPUT“B”

OUTPUT“B”

OUTPUT“D”

OUTPUT“D”

F T

Page 36: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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:

BS (Sept 2013) 36

…if (number == 1) printf(“One\n”);else if (number == 2) printf(“Two\n”);else if (number == 3) printf(“Three\n”);else printf(“Others\n”);

Enter the score: 2Two

Enter the score: 2Two

…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”);

Page 37: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill11) What are the outputs of these programs segments?

If value of score entered is 85

2) What’s the effect of re-writing the above if..else if statements to multiple if statements?

BS (Sept 2013) 37

if (score >= 90) printf(“A\n”);else if (score >= 80) printf(“B\n”);else if (score >= 70) printf(“C\n”);else if (score >= 60) printf(“D\n”);else printf(“F\n”);

if (score >= 90) printf(“A\n”);else if (score >= 80) printf(“B\n”);else if (score >= 70) printf(“C\n”);else if (score >= 60) printf(“D\n”);else printf(“F\n”);

if (score >= 90) printf(“A\n”);if (score >= 80) printf(“B\n”);if (score >= 70) printf(“C\n”);if (score >= 60) printf(“D\n”);if (score < 60) printf(“F\n”);

if (score >= 90) printf(“A\n”);if (score >= 80) printf(“B\n”);if (score >= 70) printf(“C\n”);if (score >= 60) printf(“D\n”);if (score < 60) printf(“F\n”);

Page 38: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill23) 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 2013) 38

Ritcher scale number (n) Effect n < 5.0 Little or no damage 5.0 <= n < 5.5 Some damage 5.5 <= n < 6.5 Serious damage: walls may crack or

fall 6.5 <= n < 7.5 Disaster: house or building may

collapse n >= 7.5 Catastrophe: most buildings

destroyed

Page 39: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

switch SELECTION

Topic 1-6

BS (Sept 2013) 39

Page 40: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

switch Statement• A switch statement is used to choose one choice

from multiple cases and one default case.• Syntax:

BS (Sept 2013) 40

switch (ControlVariable) { case constant 1: statement;

break; case constant-n: statement;

break; default: statement;}

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.

Page 41: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Rules for switch Statement1. The value for ‘case’ must be integer or character only.

– Examples:

2. The value checked in each ‘case’ must be constant only and not values in range.

BS (Sept 2013) 41

switch (number) {

case 1 :num += 2;break;

}

switch (number) {

case 1 :num += 2;break;

}

The value for each case is followed by colon (:).

if (number==1) num += 2;

if (color==‘R’) colorstr = ‘r’;

case 1 : case 1 : √ case >= 1 : case >= 1 : X

Page 42: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example#include <stdio.h>

void main()

{

int num;

printf(“Enter number:");

scanf("%d", &num);

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");

}

}

#include <stdio.h>

void main()

{

int num;

printf(“Enter number:");

scanf("%d", &num);

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");

}

}

BS (Sept 2013) 42

Enter number: 3Excellent (A)

CASE 1? TF

OUTPUT“Bad (D)”OUTPUT

“Bad (D)”

CASE 3?

CASE 2? TF

OUTPUT“False grade”

OUTPUT“False grade”

OUTPUT“Good (C)”

OUTPUT“Good (C)”

OUTPUT“Excellent (A)”

OUTPUT“Excellent (A)”

F T

• The logic of this switch selection is similar to if…else if

Page 43: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Omitting break Statement

BS (Sept 2013) 43

#include <stdio.h>void main(){

int majorCode;

printf("Enter your majoring code: ");scanf("%d", &majorCode);switch(majorCode){

case 1 : case 3 :case 5 : printf(“\nScience Student\n”);

break;case 2 :case 4 : printf(“\nArt Student\n”);

} /* end_switch */}

#include <stdio.h>void main(){

int majorCode;

printf("Enter your majoring code: ");scanf("%d", &majorCode);switch(majorCode){

case 1 : case 3 :case 5 : printf(“\nScience Student\n”);

break;case 2 :case 4 : printf(“\nArt Student\n”);

} /* end_switch */}

If the break statement is omitted, the execution will be carried out to the next alternatives until the next break statement is found.

Enter your majoring code: 3

Science Student

Page 44: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example• Observe the equivalent

logical expression. What can you conclude from these two program segments?

BS (Sept 2013) 44

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”);}

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”);}

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”);

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”);

Page 45: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill1. 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 2013) 45

Page 46: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

LOOPING

Topic 2

BS (Sept 2013) 46

Page 47: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Intro to Looping

BS (Sept 2013) 47

• Re-call the Swimming Pool’s Volume problem:

• Before this, we’ve learned to get our program to make decisions using Selection Structure.

• With the program, when a user key-in values of height, length, and width the computer will output the volume for one pool. However, to calculate the volume for 100 pools, the user would need to execute this program 100 times!

• So, the method 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.

A swimming pool is shaped like a big box . Write a program to find the volume of the swimming pool.

Page 48: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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:

BS (Sept 2013) 48

• To execute a number of instructions from the program for a finite, pre-determined number of time

• Loop depends of arithmetic or conditional expression.

• To execute a number of instructions from the program for a finite, pre-determined 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.

• 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.

Sentinel-controlled

Page 49: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Types of Looping

BS (Sept 2013) 49

InitializationExpressionwhile (condition){

LoopBody-statement(s)UpdateExpression

}

InitializationExpressionwhile (condition){

LoopBody-statement(s)UpdateExpression

}

do {LoopBody-statement(s) UpdateExpression

}while (condition);

do {LoopBody-statement(s) UpdateExpression

}while (condition);

for (InitializationExp; Condition; UpdateExp){LoopBody-statement(s);

}

for (InitializationExp; Condition; UpdateExp){LoopBody-statement(s);

}

1

while

2

do…while

3

for

Exp = Expression

NO semicolon (;)

Page 50: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

COUNTER-CONTROLLED LOOP DESIGN

Topic 2-1

BS (Sept 2013) 50

Page 51: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

The Concept

BS (Sept 2013) 51

• To execute a number of instructions from the program for a finite, pre-determined number of time

• Loop depends of arithmetic or conditional expression.

• To execute a number of instructions from the program for a finite, pre-determined number of time

• Loop depends of arithmetic or conditional expression.

Counter-controlled

while do…while for

Looping (Repetition Structure)

Sentinel-controlled

Page 52: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

while Statement• Syntax:

• 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 2013) 52

InitializationExpressionwhile (condition){

LoopBody statement(s)UpdateExpresssion

}

InitializationExpressionwhile (condition){

LoopBody statement(s)UpdateExpresssion

}

an expression that can return true or false

Page 53: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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.

BS (Sept 2013) 53

...int total = 1;while (total <= 3) { printf(“Total = %d\n”, total); total++;}x++;...

...int total = 1;while (total <= 3) { printf(“Total = %d\n”, total); total++;}x++;...

total is the loop controlvariable

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

WHILEtotal <= 3?

TF

SET total++

SET total=1

OUTPUT totalx++x++

Total = 1Total = 2Total = 3

Page 54: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example1

BS (Sept 2013) 54

#include<stdio.h>main ( ){

printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);

}

#include<stdio.h>main ( ){

printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);

}

#include<stdio.h>main (){

int num = 1;

while(num < 6) {

printf("Hello World\n"); num++;}

}

#include<stdio.h>main (){

int num = 1;

while(num < 6) {

printf("Hello World\n"); num++;}

}

Hello WorldHello WorldHello WorldHello WorldHello World

WHILEnum < 6?

TF

SET num++

SET num=1

OUTPUT “Hello World”EndEnd

BeginBegin

Page 55: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example2

• You may allow the user to set the number of iteration as shown in example below :

BS (Sept 2013) 55

#include<stdio.h>void main (void){

int counter=1, n=0; printf(“Number of iteration?: “); scanf(“%d”, &n);

while(counter <= n) {

printf("Hello World\n"); counter++;}

}// in this example the output varies

depending on the value of n entered by the user

#include<stdio.h>void main (void){

int counter=1, n=0; printf(“Number of iteration?: “); scanf(“%d”, &n);

while(counter <= n) {

printf("Hello World\n"); counter++;}

}// in this example the output varies

depending on the value of n entered by the user

WHILEcounter < n?

TF

SET counter++

SET counter=1, n=0

OUTPUT “Hello World”EndEnd

BeginBegin

INPUT n

Page 56: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill1) For the following code segment:

– 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 2013) 56

sum =0;count = 2;while (count <= 5){

sum = sum + count;count = count + 3;

}

sum =0;count = 2;while (count <= 5){

sum = sum + count;count = count + 3;

}

Page 57: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

do…while LOOP

Topic 2-2

BS (Sept 2013) 57

Page 58: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

2. Counter-controlled do…while Loop

• Syntax:

• 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 2013) 58

do {

LoopBody-statement(s)UpdateExpression

} while (condition);

do {

LoopBody-statement(s)UpdateExpression

} while (condition);

Semicolon here is a MUST

NO semicolon

Page 59: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example1

BS (Sept 2013) 59

#include<stdio.h>main ( ){

printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);

}

#include<stdio.h>main ( ){

printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);printf(“Hello World\n”);

}

#include<stdio.h>main (){

int num = 1;

do {

printf("Hello World\n");num++;

} while(num <=5); }

#include<stdio.h>main (){

int num = 1;

do {

printf("Hello World\n");num++;

} while(num <=5); }

EndEnd

BeginBegin

WHILE num <= 5? TF

SET num++

SET num=1

OUTPUT “Hello World”

Hello WorldHello WorldHello WorldHello WorldHello World

Page 60: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example2

• You may allow the user to set the number of iteration as shown in example below :

BS (Sept 2013) 60

#include<stdio.h>void main (void){

int counter=1, n=0; printf(“Number of iteration?: “); scanf(“%d”, &n);

do { printf("Hello World\n"); counter++;} while(counter <= n);

}// in this example the output varies

depending on the value of n entered by the user

#include<stdio.h>void main (void){

int counter=1, n=0; printf(“Number of iteration?: “); scanf(“%d”, &n);

do { printf("Hello World\n"); counter++;} while(counter <= n);

}// in this example the output varies

depending on the value of n entered by the user

INPUT n

EndEnd

BeginBegin

WHILEcounter <= n?

TF

SET counter++

SET counter=1,num=1

OUTPUT “Hello World”

Page 61: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

while Loop vs do..while Loop

BS (Sept 2013) 61

int total = 10;

while (total < 10) { printf(“Total = %d\n”, total); total++;}

printf(“Bye”);

int total = 10;

while (total < 10) { printf(“Total = %d\n”, total); total++;}

printf(“Bye”);

int total = 10;

do { printf(“Total = %d\n”, total); total++;} while (total < 10);

printf(“Bye”);

int total = 10;

do { printf(“Total = %d\n”, total); total++;} while (total < 10);

printf(“Bye”);

WHILEtotal < 10?

TF

SET total++

SET total=10

OUTPUT totalOUTPUT

“Bye”OUTPUT “Bye” WHILE

total < 10?TF

SET total++

SET total=10

OUTPUT total

OUTPUT “Bye”OUTPUT “Bye”

while loop

do…while loop

Page 62: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill1. For the following code fragment:

– 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 2013) 62

sum =0;count = 2;do {

sum = sum + count;count = count + 3;

} while (count <= 5);

sum =0;count = 2;do {

sum = sum + count;count = count + 3;

} while (count <= 5);

Page 63: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

• Syntax:

InitializationExp : initialize the loop control variableCondition : determine whether the condition or test expression

returns True or falseUpdateExp : change value of the loop control variable at the end

of each loop

BS (Sept 2013) 63

3. Counter-controlled for Loop

for (InitializationExp; Condition; UpdateExp)single LoopBody-statement;

for (InitializationExp; Condition; UpdateExp)single LoopBody-statement;

MUST semicolons

NO semicolon

for (InitializationExp; Condition; UpdateExp){

LoopBody-statement(s);}

for (InitializationExp; Condition; UpdateExp){

LoopBody-statement(s);}

Page 64: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example1

• Example:

BS (Sept 2013) 64

int total;for (total = 1; total <= 3; total++) printf(“Total = %d\n”, total);

int total;for (total = 1; total <= 3; total++) printf(“Total = %d\n”, total);

Control variable

FORtotal <= 3?

TF

SET total++

SET total=1

OUTPUT total

Total = 1Total = 2Total = 3

Page 65: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example2

• You may allow the user to set the number of iteration as shown in example below :

BS (Sept 2013) 65

#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 World\n");}

// in this example the output varies depending on the value of n entered by the user

#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 World\n");}

// in this example the output varies depending on the value of n entered by the user

FORcounter <= n?

TF

SET counter++

SET counter=1, n=0

OUTPUT “Hello World”EndEnd

BeginBegin

INPUT n

Page 66: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

while Loop vs. for Loop1

BS (Sept 2013) 66

int total = 1;

while (total <= 3) { printf(“Total = %d\n”, total); total++;}printf(“Bye”);

int total = 1;

while (total <= 3) { printf(“Total = %d\n”, total); total++;}printf(“Bye”);

WHILEtotal <= 3?

TF

SET total++

SET total=1

OUTPUT value of totalOUTPUT

“Bye”OUTPUT “Bye”

int total;

for(total=1; total<=3; total++) { printf(“Total = %d\n”, total);}printf(“Bye”);

int total;

for(total=1; total<=3; total++) { printf(“Total = %d\n”, total);}printf(“Bye”);

FOR total <= 3? TF

SET total++

SET total=1

OUTPUT value of totalOUTPUT

“Bye”OUTPUT “Bye”

Both produce same output and have similar order of execution!Because using a for loop is just another way of writing a while loop.

Page 67: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

while Loops vs. for Loops2

• Although the two are similar in their order of execution, they are different as follows:

BS (Sept 2013) 67

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

Page 68: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Omitting for Loop Expressions

• It is also possible to omit one or more of the for loop expressions.

• HOW? • Example:

BS (Sept 2013) 68

int num=1;

for (;num<=5;num++) { printf("Hello World\n");}

int num=1;

for (;num<=5;num++) { printf("Hello World\n");}

1. Assign initial value to control variable

2. Place semicolon without the expression

Page 69: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

SENTINEL-CONTROLLED LOOPS

Topic 2-2

BS (Sept 2013) 69

Page 70: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Sentinel-Controlled Loop Design

• 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 2013) 70

Page 71: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

The Concept

BS (Sept 2013) 71

while do…while for

Looping (Repetition Structure)

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.

• 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.

Sentinel-controlled

Page 72: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

1. Sentinel-Controlled while Loop

• The algorithm for sentinel-controlled while loop:

• 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 2013) 72

Read/assign a value to control variableWhile value of the control variable is not sentinel value{

process the valueread the next value

}

Read/assign a value to control variableWhile value of the control variable is not sentinel value{

process the valueread the next value

}

Value != sentinel value?

TF

Get a value

Process value

Get next value

Page 73: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

• The sentinel value in this case is ZERO

#include <stdio.h>

void main(void)

{

int num, sum = 0;

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);

}

printf(“Sum = %d\n”, sum);

}

#include <stdio.h>

void main(void)

{

int num, sum = 0;

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);

}

printf(“Sum = %d\n”, sum);

}

Example1

BS (Sept 2013) 73

Sentinel value ZERO will terminate the loop

Enter a number [zero to end]: 3Enter a number [zero to end]: -6Enter a number [zero to end]: 10Enter a number [zero to end]: 0Sum = 7

WHILE num != 0? TF

INPUT num

SET sum += num

INPUT num

OUTPUT sumOUTPUT sum

Page 74: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Example2

BS (Sept 2013) 74

#include <stdio.h>main (){ 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); } printf("Sum of %d scores: %d", count, sum);}

#include <stdio.h>main (){ 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); } printf("Sum of %d scores: %d", count, sum);}

Sentinel value -99 will terminate the loop

WHILE score!= -99?

TF

INPUT score

SET sum += score

INPUT score

OUTPUT count, sum

OUTPUT count, sum

SET count++

Enter first score (or -99 to quit): 80Enter next score (or -99 to quit): 77Enter next score (or -99 to quit): -99Sum of 2 scores: 157

Page 75: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill1. 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:

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 2013) 75

10.0 12.3 5.6 21.3 9.9

Average: 8.6

Page 76: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

2. Sentinel-controlled do/while Loop

• The algorithm for sentinel-controlled do…while loop:

• Example:

BS (Sept 2013) 76

Start do{

process the valueread a value to the control variable

} While value of the control variable is not sentinel value

Start do{

process the valueread a value to the control variable

} While value of the control variable is not sentinel value

int sum=0, score=0, count=0; do {

count++;sum += score;printf("Enter score or (-99 to quit):");scanf("%d", &score);

} while (score != -99);

printf("\nSum of %d scores: %d", count, sum);

int sum=0, score=0, count=0; do {

count++;sum += score;printf("Enter score or (-99 to quit):");scanf("%d", &score);

} while (score != -99);

printf("\nSum of %d scores: %d", count, sum);

Enter score (or -99 to quit): -99

Sum of 1 scores: 0

Page 77: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

3. Sentinel-controlled for Loop

• Example:

BS (Sept 2013) 77

#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);}

#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);}

Page 78: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill1. 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:

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 for loop.

BS (Sept 2013) 78

10.0 12.3 5.6 21.3 9.9

Average: 8.6

Page 79: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

DATA VALIDATION

Topic 3

BS (Sept 2013) 79

Page 80: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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 to 100. So, if user keys in value other than 0 to 100, 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 re-enter the input.

BS (Sept 2013) 80

Page 81: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Data Validation: if…else ifOption 1: Tell the users that they have entered a wrong input

and terminate the program.

BS (Sept 2013) 81

printf(“Enter the score: ”);

scanf(“%d”,&score);

if (score >= 90 && score <= 100) printf(“A\n”);

else if (score >= 80 && score < 90) printf(“B\n”);

else if (score >= 70 && score < 80) printf(“C\n”);

else if (score >= 60 && score < 70) printf(“D\n”);

else if (score >= 0 && score < 60 printf(“F\n”);

else printf(“Error, input should only be between 0 –

100 \n”);

Page 82: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Data Validation: while LoopOption 2(1): Tell the users that they have entered a wrong

input and ask them to re-enter the input using while loop.

BS (Sept 2013) 82

  printf(“Enter score: ”); scanf(“%d”, &score);

while (score < 0 || score > 100) {

printf(“Sorry, input must be between 0 – 100\n”); printf(“Re-enter the score: ”); scanf(“%d”,&score);

}

if (score >= 90 && score <= 100) printf(“A\n”);else if (score >= 80 && score < 90) printf(“B\n”);else if (score >= 70 && score < 80) printf(“C\n”);else if (score >= 60 && score < 70) printf(“D\n”);else printf(“F\n”);

Sentinel-controlled while loop with multiple sentinel values in the range of < zero or > 100

Page 83: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Data Validation: do..while Loop

Option 2(2): Tell the users that they have entered a wrong input and ask them to re-enter the input using do…while loop.

BS (Sept 2013) 83

  do{

printf(“Enter score: ”);

scanf(“%d”,&score);

if (score < 0 || score > 100)

printf(“Sorry, input must be between 0 – 100\n”);

}while (score < 0 || score > 100);

if (score >= 90 && score <= 100) printf(“A\n”);else if (score >= 80 && score < 90) printf(“B\n”);else if (score >= 70 && score < 80) printf(“C\n”);else if (score >= 60 && score < 70) printf(“D\n”);else printf(“F\n”);

Sentinel-controlled do…while loop with multiple sentinel values in the range of < zero or > 100

Page 84: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Data Validation: for LoopOption 2(3): Tell the users that they have entered a wrong

input and ask them to re-enter the input using for loop.

BS (Sept 2013) 84

printf("Enter the score:");

for ( scanf("%d", &score); score < 0 || score > 100; scanf("%d", &score))

{ printf(“Sorry, input must be between 0 – 100\n”); printf("Enter the score:"); }

if (score >= 90 && score <= 100) printf(“A\n”);else if (score >= 80 && score < 90) printf(“B\n”);else if (score >= 70 && score < 80) printf(“C\n”);else if (score >= 60 && score < 70) printf(“D\n”);else printf(“F\n”);

Sentinel-controlled for loop with multiple sentinel values in the range of < zero or > 100

Page 85: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

COMBINATIONS OF CONTROL STRUCTURES

Topic 4

BS (Sept 2013) 85

Page 86: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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 structure4. 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 2013) 86

Page 87: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

1. Selection Structures inside a Repetition Structure

• Example: a simple if..else inside a while loop

BS (Sept 2013) 87

WHILE x <= 3? TF

SET x++

SET x=1

OUTPUT “Kids”

OUTPUT “Bye”OUTPUT “Bye”

INPUT statusINPUT status

IF status == 1?

OUTPUT “Adults”

TF

Page 88: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

2. Repetition Structures inside a Selection Structure

• Example: a while loop inside a simple if..else

BS (Sept 2013) 88

IFstatus == 1?

TF

SET x++

SET x=1

OUTPUT “Kids”

OUTPUT “Bye”OUTPUT “Bye”

Prompt and get statusPrompt and get status

WHILE x <= 3?

OUTPUT “Adults”

TF

SET x=1SET x=1

Page 89: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Test Your Skill1. 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 2013) 89

Page 90: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

continue AND break STATEMENTS

Topic 5

BS (Sept 2013) 90

Page 91: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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:

BS (Sept 2013) 91

for (num=1;num<=5;num++) { if (num==2) break; printf("Hello World\n"); }

for (num=1;num<=5;num++) { if (num==2) break; printf("Hello World\n"); }

When the value of num is equals to 2, the program will terminate from the for loop.

OUTPUT?

Page 92: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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.

BS (Sept 2013) 92

int i; i = 0; while ( i < 20 ) {

i++; if ( i == 10)

break; }

int i; i = 0; while ( i < 20 ) {

i++; if ( i == 10)

break; }

The while loop will run, as long i is smaller then twenty. But, the while loop must stop (break) if i equals to ten

Page 93: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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).

• Example:

BS (Sept 2013) 93

for (num=1;num<=5;num++) { if (num==2) continue; /* end_if */ printf(“Number %d\n”,num); } /*end_for */

for (num=1;num<=5;num++) { if (num==2) continue; /* end_if */ printf(“Number %d\n”,num); } /*end_for */

When the value of num is equal to 2, the program will skip the printf statement and continue with the for loop.

OUTPUT?

Page 94: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

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 .

• Example:

BS (Sept 2013) 94

int i=0;

while ( i < 20 ) { i++; continue; printf("Nothing to see\n"); }

int i=0;

while ( i < 20 ) { i++; continue; printf("Nothing to see\n"); }

In the example above, the printf function is never called because of the continue statement.

Page 95: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Summary11. We can get our C programs to make decisions using Selection

Structure including if, if…else, ?: conditional operator, if…else 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, do…while loop, for loop

3. 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 2013) 95

Page 96: CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)

Summary2

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 2013) 96