Computer Programming Chapter4
Computer Programming Chapter4
CONTROL STRUCTURE
Chapter : 4 CONTROL STRUCTURE
• Content: Aim
• The use of control
structure including if, for To acknowledge student with the
concept of control structures in
and switch programming: selection control
• The use of while loop, structure and repetition control
break and goto structure
Objective
At the end of the chapter, student will
know:
✓ To explain control structures concept
✓ To write a C program using control
structures
10/10/2023 7:33:27 AM
Introduction
Sequence
Control
Structure
Selection Repetition
structure structure
10/10/2023 7:33:27 AM
Control Structure
Three types of control structures in C programming
If (condition) counter = 0;
Single C statement; while (conditional
While expression)
Sequence
{
C statement;
Double counter++;
}
If (condition) Repetitio
C statement; Selection n Do..while
else Control
C statement; Structure
counter = 0;
do
{ C statement;
counter++;
Multiple } while (x < 5);
switch (condition)
{ Case 1: C statement;
For
for (initial_value;
If (condition) break; conditional expression
C statement; Case 2: C statement; ;increment)
else if break; {
C statement; Default: C statement; 10/10/2023 7:33:27 AM
C statement;
} }
Control structure : Selection
❑ if
❑ if … else
❑ if … else if else
❑ switch case
Selection Control Structure
Used in programming to:
10/10/2023 7:33:27 AM
Selection Control Structure
Best example/case:
❖ATM bank.
❖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.
10/10/2023 7:33:27 AM
Selection Control Structure
Best example/case:
❖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”.
10/10/2023 7:33:27 AM
Selection Control Structure
10/10/2023 7:33:27 AM
Selection Control Structure
10/10/2023 7:33:27 AM
i. Single Selection
▪Use if statement.
▪Used in a situation which
▪If conditional statement is TRUE
(1), statement will be selected.
10/10/2023 7:33:27 AM
i. Single Selection (cont..)
Testing
Format
expression
10/10/2023 7:33:27 AM
i. Single Selection (cont..)
Example 1:
Yes
If grade is A, print a message ‘Excellent”
Convert to valid selection statement: grade = ‘A’ ? Print “Excellent”
Conditional
if ( grade ==‘A’) expression
printf(“Excellent !”); No
Output?
10/10/2023 7:35:41 AM
i. Single Selection (cont..)
Message “ Number is greater than
0” will be printed if only the input
Example 2: number is greater than 0
int main()
{
int nom;
printf(“Enter one number =”);
scanf(“%d”,&nom);
if (nom > 0)
printf(“Number is greater than 0”);
}
10/10/2023 7:33:27 AM
i. Single Selection (cont..)
Example 3:
Given, a = 10 and b = 12. What is the output produced?
Output?
The value of a will be
displayed if only the
expression value is 1.
10/10/2023 7:33:27 AM
i. Single Selection (cont..)
Example 4:
Answer:
printf(“Enter your age :”);
scanf(“%d”,&age);
if (age > = 18)
printf(“You are qualified to vote”);
10/10/2023 7:33:27 AM
i. Single Selection (cont..)
•If there are more than one statement to be executed under
selection, then braces { } symbol must be placed between the
executed statement .
•Example :
if ( month == 2)
{ printf(“February”);
printf(“\nEnter the day:”);
scanf(“%d”,&day);
}
10/10/2023 7:33:27 AM
i. Single Selection (cont..)
•There is a difference when not using { }.
•Example 1:
if ( carPrice == 2.00)
printf(“So cheap!”); 1
printf(“Buy more 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.
10/10/2023 7:33:27 AM
i. Single Selection (cont..)
Code segment 1
carPrice = 20000.00;
if ( carPrice == 2.00)
Output ?
printf(“So cheap!”);
printf(“Buy more car!”);
Code segment 2
carPrice = 2.00;
if ( carPrice == 2.00)
Output ?
{ printf(“So cheap!”);
printf(“Buy more car!”); }
10/10/2023 7:33:27 AM
i. Single Selection (cont..)
Example 2:
if ( carPrice == 2.00)
{ printf(“So cheap!!”);
printf(“Buy more car!”);
}
10/10/2023 7:33:27 AM
ii. Double Selection
▪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 excuted.
▪Format:
if (conditional statement)
C statement;
else
C statement;
10/10/2023 7:33:27 AM
ii. Double Selection (cont.)
Example 1:
if ( grade ==‘A’) No
printf(“Passed”);
else Print “Failed”
printf(“Failed”);
10/10/2023 8:47:22 AM
ii. Double Selection (cont.)
Example 2:
void main()
{
int nom;
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”);
}
10/10/2023 7:33:27 AM
Exercise
Determine the output of the following
a) 10 b) 5 c) 24
scanf(“%d”,&number);
if (number %2 == 0 )
{ printf(“%d is even number”,number);
printf(“\nThe value of number %d after modulo with 2 is
0”,number);
}
else
printf(“%d not even number”,nombor);
printf(“Proven!”);
10/10/2023 7:33:27 AM
iii. Multi Level Selection
▪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.
▪Format:
if (conditional expression is TRUE)
C statement;
else if (conditional expression is TRUE)
C statement;
else if (conditional expression is TRUE)
C statement;
else
C statement;
10/10/2023 7:33:27 AM
iii. Multi Level Selection (cont..)
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
10/10/2023 7:33:27 AM
iii. Multi Level Selection (cont..)
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”);
10/10/2023 7:33:27 AM
iii. Multi Level Selection (cont..)
Example 2:
Mark Grade
80-100 A
60-79 B
40-59 C
0-39 D
10/10/2023 7:33:27 AM
iii. Multi Level Selection (cont..)
ANSWER:
MAX = 0;
Example 3: if ( a > b)
{ if (a > c)
MAX = a;
else MAX?
MAX = c;
}
else {
if ( b > c)
MAX= b;
else
MAX = c;
}
10/10/2023 7:33:27 AM
iii. Multi Level Selection (cont..)
switch..case statement
• Use for multi level selection
• Similar to if..else..if but use different format
• Format:
Only Integer/
switch( conditional expression/variable) character
{
case label1: C statement;
value break; Exit from option
case label2: C statement;
break;
…
default: pernyataanC;
} Functioning like else
10/10/2023 7:33:27 AM
iii. Multi Level Selection (cont..)
switch..case statement (cont.)
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”);
}
10/10/2023 7:33:27 AM
}
iii. Multi Level Selection (cont..)
void main() void main()
{ int number; { int number;
scanf(“%d”,&number); scanf(“%d”,&number);
switch(number) if (number == 1)
{ printf(“One\n”);
case 1 : printf(“One\n”); else if (number == 2)
break; printf(“Two\n”);
case 2 : printf(“Two\n”); else if (number == 3)
break; printf(“Three\n”);
case 3 : printf(“Three\n”); else
break; printf(“Others”);
default: printf(“Others”);
} }
}
10/10/2023 7:33:27 AM
switch..cases statement
void main()
{ char gender; void main()
printf(“Enter your gender (f/m)”);
{char gender;
scanf(“%c”,&gender);
printf(“Enter your gender (f/m)”);
if (gender == ‘f’ || gender ==‘F’) scanf(“%c”,&gender);
printf(“Female\n”);
else if (gender == ‘m’ || gender== ‘M’) switch(gender)
printf(“Lelaki\n”); {
else case ‘f’:
printf(“Invalid”); case ‘F’:printf(“Female\n”);
} break;
case ‘m’:
case ‘F’:printf(“Male\n”);
break;
default: printf(“Invalid”);
}
}
10/10/2023 7:33:27 AM
Exercise
Convert the following if..else statement to
switch..case statement
if ( warna == ‘m’)
printf(“\nMerah tanda keberanian”);
else if( warna == ‘b’)
printf(“\nBiru tanda perpaduan”);
else if( warna == ‘k’)
printf(“\nKuning tanda kedaulatan”);
else
printf(“\nRalat”);
10/10/2023 7:33:27 AM
Exercise
4. Convert the following C segment code
which contains switch..case statement to if
..else statement. if(number%2==0)
{even++;
printf("Total even numbers
switch (number %2) :%d",even);
{case 0 : even++; }
printf(“Total even numbers:%d”,even); else if(number%2!=0)
break; {odd++;
case 1 : odd++; printf("Total odd
printf(“Total odd numbers:%d”,odd); numbers:%d",odd);
break; }
default: printf(“Nothing happened”); Else
} printf("Nothing happened");
10/10/2023 5:31:21 PM
Lab Exercise 4a : Submit during lab session
Question 1
1.Write an algorithm ( flowchart) then write a program using if … else statement to display student’s
bachelor class of graduation based on Cumulative Grade Point Average (CGPA) by referring to the table
below.
CGPA Class of Graduation
>= 3.70 First class honours
3.00 – 3.69 Upper second class honours
2.30 – 2.99 Lower second class honours
2.00 – 2.29 Third class honours
< 2.00 Failed
Lab Exercise 4a : Submit during lab session
Question 2
The following is simple program that computes a
salesperson’s pay. The salesperson gets a basic flat rate of
RM4.10 per hour. In addition, if the sales are more than
RM8500, the salesperson also receives an additional
RM500 as a bonus.
Write an algorithm (pseudo code ) then write an interactive program that using
switch … case statement to calculate and display the area of a rectangle OR
triangle OR circle. The selection depends on the character entered by the user -
R/r for rectangle and T/t for triangle and C/c for circle. You may use the
following equation:
If (condition) Repetitio
C statement; Selection n Do..while
else Control
C statement; Structure
Multiple
switch (condition)
{ Case 1: C statement;
If (condition) break; For
C statement; Case 2: C statement;
else if break;
C statement; Default: C statement;
}
10/10/2023 3:26:07 PM
Repetition
How will you solve this?
10/10/2023 7:33:27 AM
Solution? Sequence Style
void main()
{ int nom1,nom2,nom3,nom4,nom5;
10/10/2023 7:33:27 AM
HOW…?
How if you want to enter marks
for more than 50 students ?
10/10/2023 7:33:27 AM
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:
1. while loop
2. do..while loop
3. for loop
10/10/2023 7:33:27 AM
i. while loop
▪Use while statement
▪Statement will be repeated if the condition is
TRUE.
▪Format :
IMPORTANT!
counter = 0; 1. Counter
2. Counter initialization
while (conditional expression) 3. Conditional expression testing
{ 4. Increment/decrement of counter
C statement;
counter++;
}
Repeated statements
10/10/2023 7:33:27 AM
i. while loop (cont..)
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
10/10/2023 7:33:27 AM
Example 1:
void main() void main()
{ int nom1,nom2,nom3,nom4,nom5; { int nom;
int i; counter
printf(“\nEnter one number :”);
i =0;
scanf(“%d”,&nom1);
printf(“\ nEnter one number :”);
while(i <5) condition
scanf(“%d”,&nom2); {
printf(“\ nEnter one number :”); printf(“\ nEnter one number :”);
scanf(“%d”,&nom3); scanf(“%d”,&nom);
printf(“\ nEnter one number :”); i++;
scanf(“%d”,&nom1); }
printf(“\ nEnter one number :”); }
scanf(“%d”,&nom5);
}
increment
10/10/2023 7:33:27 AM
i. while loop (cont..)
5 AM
10/10/2023 7:33:27 5<5 = F
i. while loop (cont..)
Example 2:
a = 1;
while ( a <= 4)
{ printf(“Number %d”,a);
a++;
}
Number 1Number 2Number 3Number 4
10/10/2023 7:33:27 AM
i. while loop (cont..)
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 (
while(j<=5) )
{
3 {
printf("%d\n",j);
4 j++;
5 }
}
10/10/2023 7:33:27 AM
i. while loop (cont..)
Example 4:
1 2 3 4 5 6
Counter
2 4 6 8 10 12
Output!
10/10/2023 7:33:27 AM
i. while loop (cont..)
Answer:
A = 1;
B = 2;
while ( A < = 6)
{
printf(“\t%d”, B);
B = B + 2;
A++;
}
10/10/2023 7:33:27 AM
i. while loop (cont..)
Example 5:
Using while loop statement, write a valid C segment code
to input/accept the name of 60 students.
Jawapan:
x = 1;
while (x < =60)
{ printf(“Enter student’s name :”);
gets(name);
x++;
}
10/10/2023 7:33:27 AM
i. while loop (cont..)
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);
}
10/10/2023 7:33:27 AM
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);
}
}
10/10/2023 7:33:27 AM
ii. do..while loop
10/10/2023 7:33:27 AM
ii. do..while loop (cont..)
Differences between while & do..while loop
While loop do..while loop
Loop is tested before Loop is tested after
repetition can be done repetition is done
while ( a < 4)
{ …….. } do
{
} while ( a<4);
Possibility of repeated loop Possibility of repeated loop
is 0 is 1
10/10/2023 7:33:27 AM
ii. do..while loop (cont..)
Example 1 :
Determine the output: Output
x = 0;
y = 2;
y=4
do
y=8
{ y = 2 * y;
y = 16
printf(“ \n y = %d”, y);
y = 32
x++;
y = 64
} while (x < 6);
10/10/2023 7:33:27 AM
ii. do..while loop (cont..)
i = 2;
i= 2;
j = 1;
j = 1;
do
while (i < 8)
{ i++;
{ i++;
printf(“ i x j = %d”, i * j);
printf(“ i x j = %d”, i * j);
} while (i < 8);
}
do..while while
10/10/2023 7:33:27 AM
ii. do..while loop (cont..)
bil = 10;
do
{ printf(“ %d ”, bil );
10 9 8 7 6
bil--;
} while (bil > 5);
10/10/2023 7:33:27 AM
ii. for loop
Repeated
statements
10/10/2023 7:33:27 AM
ii. for loop (cont..)
8
7
6
Example: .
.
.
int bil, nilai = 3; …….(Non-stop looping)
10/10/2023 7:33:27 AM
ii. for loop (cont..)
10/10/2023 7:33:27 AM
Exercise
1.Determine the output of the following do..while statement using trace table:
i= 10;
jumlah=0;
do{
jumlah += i * 2;
i -=2;
printf(“i%d\t”,jumlah);
}while(i >=0);
10/10/2023 7:33:27 AM
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++;
}
10/10/2023 7:33:27 AM
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
6 15 6<6=F
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 for (xy = 0; xy < =6;xy ++)
Value = 5 printf(“\nValue = %d”, xy + 3);
Value = 6
Value = 7
Value = 8
Value = 9
10/10/2023 7:33:27 AM
Recap: Control Structure
Three types of control structures in C programming
If (condition) counter = 0;
Single C statement; while (conditional
While expression)
Sequence
{
C statement;
Double counter++;
}
If (condition) Repetitio
C statement; Selection n Do..while
else Control
C statement; Structure
counter = 0;
do
{ C statement;
counter++;
Multiple } while (x < 5);
switch (condition)
{ Case 1: C statement;
For
for (initial_value;
If (condition) break; conditional expression
C statement; Case 2: C statement; ;increment)
else if break; {
C statement; Default: C statement; 10/10/2023 7:33:27 AM
C statement;
} }
Lab exercise 4b : Submit during lab session
What is your mark? (-1 to end) 87.0
Exercise 1 What is your mark? (-1 to end) 89.0
What is your mark? (-1 to end) 96.0
Change the program below by using while loop What is your mark? (-1 to end) 78.0
What is your mark? (-1 to end) 99.0
What is your mark? (-1 to end) 87.0
What is your mark? (-1 to end) 89.0
What is your mark? (-1 to end) -1
Exercise 3
Write the complete program to print the odd numbers from 20 to 1.
Nested for loops
Outlines of two nested loops
Example 1
Example 2
Next Chapter : 6
• ARRAY
• 6.1 One and two dimensions array
• 6.2 Functions swapping between array
• 6.3 Sorting and simple searching of array
• 6.4 Two dimensions array and function