You are on page 1of 72

BIC 10204 Algorithm and Programming

CHAPTER 5
Control Statement

1
Objectives

At the end of this chapter, student should be able


to:
 To explain control structures concept
 To write a C program using control
structures

2
Introduction

 Three (3) types of control structures in


C programming

Sequence

Control
Structure

Selection Repetition
structure structure
Do we have choices
in life?

4
Selection Control Structure

 Used in programming to:


 offer choice of interests to user of a
system,
 restrict / limit to only one operation/
process in a system to be executed at a
time,
 allow user to choose only one selection of
process/ operation at a time from a
system,
 execute a process/operation based on
selection.
5
Selection Control Structure (2)
 Best example/case: ATM system where
 User can only choose one operation at a time.
 If user choose to withdraw money, only the
withdrawal screen which allows the user to enter
the amount of money to withdraw will be displayed.
 If user want to do another operation, such as
checking money balance they have to get back to
the main menu/ screen or select another process.
 In general, the ATM processes are controlled by
some restrictions or rules which is written using
selection control structure (using particular
programming language).
 The concept is “one selection, one operation”.

6
Selection Control Structure (3)

CINBANK ATM
Please select the menu

< Withdrawal Check Account Balance >

< Change pin number Others >

7
Selection Control Structure (4)

 How decision is made when user make


their selection from the ATM menu?
 The system will check the input and
compares the selection with the
conditions set in the system. If the
input matches the setting conditions,
the corresponding menu will be
displayed.

8
Selection Control Structure (5)

 Choose only one instruction to be executed.


 Selection will be done if only the conditional
statement is TRUE.
 Types of selection control structure:
i. Single selection (if)
ii. Two level selection (if-else)
iii. Multi level selection (if-else-
if)
9
i. Single Selection (if)
 Use if statement.
 Used in a situation where
 If conditional statement is TRUE (1), statement will
be selected/displayed.

if (x != 0.0) if (condition)
a = a * x; statement-1;

 Above if statement shows “if x is not equal to 0.0”,


then statement-1 “a=a*x” is executed.
 How about if x=0?
 statement “a=a*x” is not executed.
10
i. Single Selection (if) (2)

Testing
Format

Reserved
if (conditional expression)
word C statement;

Consist of: Example:


Output statement/ age > 21
Input statement/ baki >= wangkeluar

expression

11
i. Single Selection (if) (3)
Example 1:

If grade is A, print a message ‘Excellent”


Convert to valid selection statement: Conditional

if ( grade ==‘A’) expression


printf(“Excellent !”);

Output?
12
i. Single Selection (if) (4)
Convert to flowchart:

Yes
grade = ‘A’ ? Print “Excellent”

No

13
i. Single Selection (if) (5)

Message “Number is
greater than 0” will be
Example 2: printed if only the input
void main() number is greater than 0
{
int nom;
printf(“Enter one number =”);
scanf(“%d”,&nom);
if(nom>0)
printf(“Number is greater than 0”);
}

14
i. Single Selection (if) (6)
Example 3:

Given, a = 10 and b = 12. What is the output produced?

if(a>b && a!=9)


printf(“The value of a is %d”, a);

Output?
The value of a will be
displayed if only the
expression value is 1.

15
i. Single Selection (if) (7)
Example 4:

Write a C code segment which prompt user to enter age. If


age is greater or equal to 18, display a message “You are
qualified to vote”.

Answer:
printf(“Enter your age :”);
scanf(“%d”,&age);
if(age>= 18)
printf(“You are qualified to vote”);
16
i. Single Selection (if) (8)
 If there are more than one statement to be executed under
selection, then { } symbol must be placed between the
executed statement .
 Example :
if (month == 2)
{
printf(“February”);
printf(“\nEnter the day:”);
scanf(“%d”,&day);
}
17
i. Single Selection (if) (9)
 There is a difference when not using { }.
 Example 1:

if (carCapacity>1.2 && carCapacity<=1.4)


printf(“Pay RM=100 for road tax\n”); 1
printf(“So cheap! Can buy other car!”);
2

 The first statement (1) will be executed if only the


conditional statement is TRUE.
 The second statement (2) will be executed even the if
statement is FALSE.
18
i. Single Selection (if) (10)
Code segment 1:
carCapacity = 1.4;
if (carCapacity>1.2 && carCapacity<=1.4)
printf(“Pay RM=100 for road tax\n”); Output ?
printf(“So cheap! Can buy other car!”);

Code segment 2:
carCapacity = 1.4;
if (carCapacity>1.2 && carCapacity<=1.4)
{
printf(“Pay RM=100 for road tax\n”);
Output ?
printf(“So cheap! Can buy other car!”);
}

19
i. Single Selection (if) (11)
Example 2:

if (carCapacity>1.2 && carCapacity<=1.4)


{
printf(“Pay RM=100 for road tax\n”);
printf(“So cheap! Can buy other car!”);
}

 If the car capacity is 1.2, then no output displayed.


 However if the car capacity is above 1.2 and less than or equal to 1.4,
then the following output will be displayed
Pay RM=100 for road tax
So cheap! Can buy other car!
20
Exercise

Convert the following statements to valid C statements:

a) if mark is between 80 to 84, then the student’s grade


is A-.
b) if mark is between 85 to 100, print a message “Grade
is A”.
c) if salary is greater than RM2500.00, then pay the tax.

21
ii. Double Selection
(if-else)
 Use if..else statement.
 Use in situation which provide 2 condition, but only 1’
selection can be made.
 If the condition is TRUE (1), then the first statement
will be executed.
 If not, the next selection will be executed.
 Format:
if (conditional statement)
C statement;
else
C statement;
22
ii. Double Selection
(if-else) (2)
Example 1:

If grade = ‘A’, print a message “You pass ”


Otherwise, print a message “You fail”

Convert to a valid C selection statement:

if ( grade ==‘A’)
printf(“You pass”);
else
printf(“You fail”);
23
ii. Double Selection
(if-else) (3)
Convert to flow chart:

Yes
if grade = ‘A’ Print “You pass”

No

Print “You fail”

24
ii. Double Selection
(if-else) (4)
Example 2: What will be
displayed if
void main() number entered
{ from keyboard is
int nom; 18 ?
printf(“Enter one number ?”);
scanf(“%d”,&nom);

if (nom>0)
printf(“Number is greater than 0”);
else
printf(“Number is less than 0”);
printf(“Thank You”);
}

25
ii. Double Selection
(if-else) (5)
Example 2:
void main()
{
int nom;
printf(“Enter one number ?”);
scanf(“%d”,&nom); if number
entered
if (nom>0) from
printf(“Number is greater than 0”); keyboard
else is 0 ?
printf(“Number is less than 0”);
printf(“Thank You”);
}

26
Double Selection
(if-else) (6)
conditional ?: operator
 What is meant by this statement
x=(y>z) ? y : z;
 ?: is a good shorthand for longer if-else
 Syntax
expression1 ? expression2 : expression3
 if expression1 is true, expression2 is evaluated. If
expression1 is false, expression3 is evaluated
 ?: need 3 operands
27
Double Selection
(if-else) (7)
conditional ?: operator
double income, expenses, savings, deficit, interest;

printf ("Enter your income and expenses:\n");


scanf ("%lf %lf", &income, &expenses);
printf ("\n\n");

if (income >expenses)
{
savings = income - expenses ;
printf ("\nYou are saving money. \n"
"Your savings for this month are: RM%8.2f",savings);
}
else
{
deficit = expenses - income ;
printf ("\nYou are running a deficit. \n"
"Your deficit for this month is : RM%8.2f",deficit);
}
interest = (deficit > 0.0) ? (0.05*deficit) : (0.0) ;
28
printf ("\nThe interest you owe on your debt is RM%.2f \n", interest);
Exercise
Determine what will be displayed if the number is
a) 10 b) 5 c) 24

printf("Enter any number\n");


scanf("%d", &number);
if (number%2 == 0 )
{
printf("%d is an even number", number);
printf("\nAny number mode to 2 is 0");
}
else
printf("\n%d is not even",number);
printf("Proof!");

29
iii. Multi Level Selection
(if–else-if)
 Use if..else..if statement
 Use in a situation which requires/provides two
choices.
 If the conditional is TRUE (1), then selection will
be made.
if (conditional expression is TRUE)
 Format: C statement;
else if (conditional expression is TRUE)
C statement;
else if (conditional expression is TRUE)
C statement;
else
C statement;
30
iii. Multi Level Selection
(if–else-if) (2)
Example 1:

Write the selection control structure statements in C to


produce the following output based on the input:
Input Output
1 One
2 Two
3 Three
4 Four
5 Five
31
iii. Multi Level Selection
(if–else-if) (3)
Answer:

if(input==1)
printf(“\nOne”);
else if(input==2)
printf(“\nTwo”);
else if(input==3)
printf(“\nThree”);
else if(input==4)
printf(“\nFour”);
else
printf(“\nFive”);
32
iii. Multi Level Selection
(if–else-if) (4)
Example 2:

Write C statements to determine student’s grade based


on their marks as shown in the following table:
Mark Grade
80-100 A
60-79 B
40-59 C
0-39 D

33
iii. Multi Level Selection
(if–else-if) (5)
ANSWER:

if(mark>=80 && mark<=100)


grade = ‘A’;
else if(mark>=60 && mark<=79)
grade = ‘B’;
else if(mark>=40 && mark<=59)
grade = ‘C’
else
grade = ‘D’;

printf(“The student’s grade is %c”, grade);


34
iii. Multi Level Selection
(if–else-if) (6)
Example 3:
Given a= 8 , b = 3 and c = 5, What is the value of MAX?

MAX = 0;
if ( a > b)
{ if (a > c)
MAX = a;
else
MAX = c;
}
else {
MAX?
if ( b > c)
MAX= b;
else
MAX = c;
} 35
iii. Multi Level Selection (7)
switch..case statement
 #Use for multi level selection
 #Similar to if..else..if but use different format
 #Format:
switch (conditional expression/variable) only integer/
{ character data type
case label1:
C statement;
value
break; exit from the option
case label2:
C statement;
break;

default:
functioning like C statement;
else
} 36
iii. Multi Level Selection (8)
switch..case statement (2)
Example

void main()
{ int number;
scanf(“%d”,&number);

switch(number) variable
{
case 1 : printf(“One\n”);
break;
case 2 : printf(“Two\n”); action
The value of break;
variable number case 3 : printf(“Three\n”);
break;
default: printf(“Others”);
}
} 37
iii. Multi Level Selection
(if–else-if) (9)
void main() void main()
{ {
int number; int number;
scanf("%d", &number); scanf(“%d”, &number);

switch(number) if (number == 1)
{ printf(“One\n”);
case 1: else if (number == 2)
printf("One\n"); printf(“Two\n”);
break; else if (number == 3)
case 2 : printf(“Three\n”);
printf("Two\n"); else
break; printf(“Others”);
case 3 : }
printf("Three\n");
break;
default:
printf("Others");
}
38
}
iii. Multi Level Selection (10)
switch..case statement
void main() void main()
{ {
char gender; char gender;
printf("Enter your gender (f/m)"); printf("Enter your gender (f/m)");
scanf("%c", &gender); scanf("%c", &gender);

if (gender == 'f' switch(gender)


|| gender =='F') {
printf("Female\n"); case 'f':
else if (gender == 'm' case 'F':
|| gender== 'M') printf("Female\n");
printf("Male\n"); break;
else case 'm':
printf("Invalid"); case 'M':
} printf("Male\n");
break;
default: printf("Invalid");
}
} 39
Exercise
Convert the following if..else statement to
switch..case statement

if ( color == ‘r’)
printf(“\nRed means brave”);
else if( color == ‘b’)
printf(“\nBlue means fusion”);
else if( color == ‘y’)
printf(“\Yellow means royal”);
else
printf(“\nBug”);

40
Nested if-else
#Means an if-else control structure can be contained within
another if-else control structure
#For example
Weekdays (Monday-Friday)
07:00-19:00 Lectures
19:01-21:30 Rest
21:31-23:00 Assignments/ Study
23:01-05:00 Sleep
Weekends (Saturday-Sunday)
07:00-10:00 Washing clothes, tidy room
Saturday
10:01-14:00 Outing
14:01-21:30 Rest
21:31-23:00 Assignments/ Study
23:01-05:00 Sleep
Sunday
10.00-23:00 Assignments/ Study/ Rest
41
int day;
float time;
printf (" Type the day and time of interest\n\n");
scanf ("%d%f", &day,&time);
if (day<= 5)
{ if (time>=7.00 && time<=19.00)
printf (" Lectures \n\n");
else if(time>19.00 && time<=21.30)
printf (" Rest \n\n");
else if(time>21.30 && time<=23.00)
printf (" Assignments/ Study \n\n");
else
printf("Sleep\n\n");
}
else
{ if (time>=7.00 && time<=10.00)
printf (" Watching clothes and tidy room \n\n");
if(day==6)
{ if(time>10.00 && time<=14.00)
printf (" Outing \n\n");
else if(time>14.00 && time<=21.30)
printf (" Rest \n\n");
else if(time>21.30 && time<=23.00)
printf (" Assignments/ Study \n\n");
else
printf("Sleep\n\n");
}
else
if(time>10.00)
printf (" Assignments/ Study/ Rest
42 \n\n");
}
How will you solve this?

Write a C program which


will accept five integer
numbers

43
Solution?
void main()
{
int nom1,nom2,nom3,nom4,nom5; Output:
printf(“\nEnter one number:”);
Enter one number : nom1
scanf(“%d”,&nom1);
printf(“\ nEnter one number :”);
Enter one number : nom2
scanf(“%d”,&nom2);
printf(“\ nEnter one number :”);
Enter one number : nom3
scanf(“%d”,&nom3); Enter one number :
printf(“\ nEnter one number :”); nom4
scanf(“%d”,&nom1);
Enter one number : nom5
printf(“\ nEnter one number :”);
scanf(“%d”,&nom5);
}

44
HOW…?

How if you want to enter marks


for more than 50 students ?

What if there are hundreds of


data to be inserted into the
system?

45
Repetition Control Structure
 #Enable statements to be repeated.
 #While the value of conditional expression is
TRUE, statements will be repeated.
 #Repetition will be terminated if the
conditional expression is 0 (FALSE).
 #Type of repetition/loop control structures:
i. while loop
ii. do..while loop
iii.for loop
46
i. while loop
 #Use while statement
 #Statement will be repeated if the condition is
TRUE.
 #Format :
IMPORTANT!
counter = 0; 1. Counter initialization
while (conditional expression) 3. Conditional expression testing
4. Increment/decrement of counter
{
C statement;
counter++;
}
Repeated statements

47
i. while loop (2)
 Important aspects:
 1.Counter Initialization
 counter is a variable.
 Must be declared as an integer.
 Used to count amount of loops.
 Can be initialized starting from any value.
 Example : x = 0; a= 1; I = 3;

 2. Conditional Expression
 Logical (>,<,==,!=,<=,>=) symbol is used.
 Used to ensure the loop/repetition is occurred.

48
i. while loop (3)
• “i” is counter and it is tested
• Example: • Another variable can be used
in the testing process
while ( i < 4)

3. Increment/decrement value of counter


• Used to increase/ decrease the value of counter
for the statements to repeat.
• If not, infinite loop will occurred
• Example:
i ++;
++a;
y--;
:: increment is used if the initial value of counter is
less while decrement is used if the initial value of counter
is high.
49
i. while loop (4)
Example 1:

void main() void main()


{ int nom1,nom2,nom3,nom4,nom5; { int nom; counter
int i;
printf(“\n Enter one number :”); i =0;
scanf(“%d”,&nom1); while(i<5) condition
printf(“\n Enter one number :”); {
printf(“\n Enter one number:”);
scanf(“%d”,&nom2);
scanf(“%d”, &nom);
printf(“\n Enter one number :”);
i++;
scanf(“%d”,&nom3); }
printf(“\n Enter one number :”); }
scanf(“%d”,&nom4);
increment
printf(“\n Enter one number :”);
scanf(“%d”,&nom5);
}

50
i. while loop (5)
HOW while loop works??

Trace Table

i i< 5 output nom i++


0 0<5 = T Enter one number : 3 1

1 1<5 = T Enter one number : 5 2

2 2<5 = T Enter one number : 1 3

3 3<5 = T Enter one number : 2 4

4 3<5 = T Enter one number : 15 5

5 5<5 = F
51
i. while loop (6)
Example 2:

Determine the output of the following while loop statement :

a = 1;
while ( a <= 4)
{
printf(“Number %d”,a);
a++;
}
Number 1Number 2Number 3Number 4
52
i. while loop (7)
Example 3:

Write a valid C segment code/fragment to display the following


output using while loop statement.

Output
Answer:
1 int j=1;
2 while(j<=5)
3 {
4 printf("%d\n", j);
5 j++;
}

53
i. while loop (8)
Example 4:

Write a valid C statement to display the following output using


while loop statement.

1 2 3 4 5 6
Counter

2 4 6 8 10 12

Output!

54
i. while loop (9)
Answer:

int k=0;
int bil=1;
while(bil<=6)
{
k=k+2;
printf("%d\t",k);
bil++;
}

55
i. while loop (10)
Example 5:

 Using while loop statement, write a valid C segment code


to input/ accept the name of 60 students.

Answer
x = 1;
while (x < =60)
{ printf(“Enter student’s name :”);
gets(name);
x++;
}

56
i. while loop (11)
Example 6:

//A program to count the addition of five numbers


#include <stdio.h>
void main()
{ int number, y, total =0;
y = 0;
while( y < 5)
{ printf(“\n Enter a number”);
scanf(“%d”, &number);
total = total + number;
y++;
}
printf(“The addition result of five numbers is %d”,total);
}

57
i. while loop (12)
Example 7:

//A C program to accept several numbers

#include <stdio.h>
void main()
{
int bil,i, nom;
i=1;
printf(“\n Enter amount of numbers :”);
scanf(“%d”,&bil);
while( i < = bil) Compared with counter
{
printf(“\nEnter a number:”);
scanf(“%d”, &nom);
i++;
printf(“The input number is %d”, nom);
}
}

58
ii. do..while loop
 #Use do..while statement
 #Repetition will occurred if condition is TRUE (1)
 #Similar to while, must include 3 important things
 #Format :

counter = 0;
do
{
C statement;
counter++; Repeated statements
} while (x < 5);

59
ii. do..while loop (2)
Differences between while & do..while loop

While loop do..while loop


Loop is tested before Loop is tested after repetition
repetition can be done is done

while ( a < 4) do
{ {
… …
} } while ( a<4);

Possibility of repeated loop Possibility of repeated loop


is 0 is 1
60
ii. do..while loop (3)
Example 1 :
Determine the output:
Output
int x = 0,y = 2; y=4
do y=8
{
y = 16
y = 2 * y;
printf(" \n y = %d", y); y = 32
x++; y = 64
} while (x<6); y = 128

61
ii. do..while loop (4)
Example 2: Convert the following do..while loop to while loop

int i = 2,j = 1;
do
{ i++;
printf("%d x %d = %d\n", i,j,i * j);
} while (i < 8);

do..while
int i = 2,j = 1;
while (i < 8)
{ i++;
printf("%d x %d = %d\n", i,j,i * j);
}

62 while
ii. do..while loop (5)
Example 3 : Determine the output

bil = 10;
do
{
printf(“ %d ”, bil );
bil--;
}while (bil > 5);

10 9 8 7 6

63
iii. for loop
 #Use for loop
 #Repeat statement until condition is FALSE
 #Similar to while loop, must includes 3 important things
 #Format :

for (initial_value; conditional expression; increment)


{
C statement;
}

Repeated
statements
64
iii. for loop (2)
Example:

int num, value=3; Output?

for (num=5; value>0; num--)


{
if(value % 2 == 1)
8
printf(“\n %d”, num + value);
7 }
6
.
.
.
65
…….(Non-stop looping)
iii. for loop (3)
Syntax comparison between loops

while.. do..while for


i=0; i=0; for (i=0;i<5;i++)
while(i<5) do {
{ {
i++; i++;
} }while(i<5); }

66
Exercise
1. Determine the output of the following do..while statement using
trace table:

i= 10; 20 36 48 56 60 60
total=0;
do{
total += i * 2;
i -=2;
printf(“%d\t”,total);
}while(i >=0);

int
2. Rewrite the following fortotal = 0;
loop statement using do..while
statement. int i=1;
total = 0; do{
for ( i = 1; i < 10; i +=2) total = total + i;
{ i+=2;
total = total + i; }while(i<10);
} printf("Total is %d\n", total);
printf(“Total is %d\n”, total);
67
Exercise
3. Using trace table, determine the output of the following repetition
control structure statements:

a) x=1;
total = 0;
while (x < 6)
{
printf(“\n%d%d”,x,total);
total +=x;
x++;
}

b) for (xy=0; xy<=6; xy++)


printf(“\nValue = %d”, xy + 3);

68
Trace Table for 3 (a)
x total x< 6 output total=total+x x++
1 0 1<6=T 10 0+1=1 2

2 1 2<6=T 21 1+2=3 3

3 3 3<6=T 33 3+3=6 4

4 6 4<6=T 46 6+4=10 5

5 10 5<6=T 510 10+5=15 6

6 15 6<6=F

x=1;
The output is total = 0;
10 while (x < 6)
21 {
33 printf(“\n%d %d”, x, total);
46 total +=x;
510 x++;
} 69
Trace Table for 3 (b)
xy xy<= 6 xy+3 output xy++
0 0<=6=T 3 Value=3 1

1 1<=6=T 4 Value=4 2
2 2<=6=T 5 Value=5 3

3 3<=6=T 6 Value=6 4

4 4<=6=T 7 Value=7 5

5 5<=6=T 8 Value=8 6

6 6<=6=T 9 Value=9 7

7 7<=6=F

The output is
Value = 3
Value = 4
Value = 5 for (xy = 0; xy < =6;xy ++)
Value = 6 printf(“\nValue = %d”, xy + 3);
Value = 7
Value = 8
Value = 9 70
Exercise

4. Convert the following C segment code which contains


switch..case statement to if ..else statement.

switch (number%2)
{
if(number%2==0)
{ case 0 : even++;
even++;
printf(“Total even numbers :%d”,even);
printf("Total
break; even numbers :%d", even);
} case 1 : odd++;
else if(number%2!=0)
printf(“Total odd numbers:%d”,odd);
{ break;
odd++;
default: printf(“Nothing happened”);
} printf("Total odd numbers:%d", odd);
}
else
printf("Nothing happened");
71
DEVELOP A COMPLETE C PROGRAM

As a software engineer in Meteorologist Department, you have requested to


develop C program in order to detect hurricane categories based on the wind speed
as shown in Table 1. The program will ask user to enter wind speeds, analyze the
category for each wind speeds and print the information based on the category.
Table 1: The scale of hurricane intensities

Category Wind speeds Information


1 From 74 to 95 mph Minimal damage to property
2 From 96 to 110 mph Moderate damage to property
3 From 111 to 130 mph Extensive damage to property
4 From 131 to 155 mph Extreme damage to property
5 Over 155 mph Catastrophic damage to property
By using the category, displaying information function will display the
appropriate information.
72

You might also like