You are on page 1of 72

Chapter 3: Control Structure

Muhammad Taufiq
Department of Information and Communications Technology, , IIUM
Learning Outcome
• Write program using logical and relational operators by incorporating them in
if-else and switch statements
• Describe the basic looping concept
• Differentiate between pre-test and post-test loops
• Describe the concept of event-controlled, counter-controlled and sentinel-
controlled loops
• Select the best loop construct for a given problem
• Write programs by using the while, for, or do-while statements

2
Objectives
• Understand C expression concept – operators, precedence &
associativity and statements.
• Capable to identify usage of each operators and expressions
• To be able to construct a simple and complex logical (Boolean)
expression
• To evaluate a given condition
• To be able to construct (identify, analyze) selection and
repetition problems

3
What in This Chapter
• (Part 1) Relational and Logical Expression
• Selective Structure If else..
• 2-Way (if-else, Null statement) Switch CASE

• Multi way (Switch case, else-if) !=, >, ==


• (Part 2) Repetitive Structure &&, ||, !
• While loop, do-while, For loop While loop
• Event/condition controlled For
• Counter controlled
• Sentinel controlled
• Nested Loop 4
5 Scratch
Source: CS50 2019 - Lecture 0 - Computational Thinking,
Operator & Operand

x-y
Operand
Operand (y)
(x)

Operator (-)

6
Relational Operators
• Relational operator – use for data comparisons. (equal, less,
greater, etc)
• Used with if statements
• The result is TRUE (1) or FALSE (0)

Book page: 58

7
Type of Relational Operator
Operator Description Example

== equal to x==y

> greater than x>y

< less than x<y

>= greater or equal x>=y

<= less or equal x<=y

!= Not equal to x!=y


8
Logical Operators
Logical Operator – use to combine more than one relational
test. Also known as compound relational operators.

9
Type of Logical Operator
Operator Meaning Example

&& AND ((x<y)&&(x!=0))

((x<y)||(x!=0))
|| OR
! NOT !(x>=y)

10
Relational and Logical Expression

int a = 10, b = 50;


char ch1 = ‘A’;
float x = 9.5;

Relational + Logical Expression Value


a < b && ch1 = = ‘A’ 1 (true)
b – x < 5.0 | | ch1 ! 0 (false)
= ‘A’

11
Example
(age>20)==(Bonus=500)||(Bonus=0);

If value for age is >20, value for Bonus = 500 otherwise


Bonus=0;

If condition for age>20 is TRUE, TRUE expression will be


execute, if condition is FALSE, FALSE expression will be
execute.

12
Q&A
Overview
• Algorithm/Statements fall into three general types:
1. Assignment, where values, usually the results of calculations, are
stored in variables.
2. Input / Output, data is read in or printed out.
3. Control, the program makes a decision about what to do next.

Inputs Algorithms Outputs

14
Control Statements
• 3 types of control statements;
• Sequential
• Selection
• Repetition/Loop
• In real problems, the solution derived from combination of
above types
• One the efficiency aspects of program is how control structure
is develop – run time

15
Sequential Control Statement (Chapter 2)
• One way directly from top to bottom start

#include <stdio.h> input


Basic salary
int main() allowances

{
float Total income = basic salary
+ allowances
b_sal,allw,T_inc;
scanf(“%f”,&b_sal); Print total
income
scanf(“%f”,&allw);
T_inc = b_sal+allw; end

printf(“%f”,T_inc);
}

16
Selection Control Statement
• The basic decision statement is two-way selection which
describe either true or false.
• C implement two-way selection with the if … else statement.
• Types of Control Statement:
• Single Selection
false true
• Two-Way Selection condition
• Multi-Selection
statement1 statement2

17
Rules of if…else
• The expression must be enclosed in parentheses ( )
• No semicolon (;) after if…else statement.
• Both true or false statements can be any statements or null
statement.

18
Single-Selection Statement
• Logic flow of if … statement

true

condition

false
statement2

19
Example: Single-Selection Statement
• It is possible to use the if part without the else.

if (temperature < 0) true


{ condition
printf("Frozen\n");
} false
statement2

20
#include <stdio.h>

int main()
{
int a;

printf(“Please enter an interger :”);


scanf(“%d”,&a);

if (a>0) /*To test positive integer*/


{
printf(“\n You have entered positive number.”);
}

if (a<0) /*To test negative integer*/


{
printf(“\n You have entered negative number.”);
}

return 0;
}

21
Two-Way Selection Statement
• Logic flow of if … else statement

false true
condition

statement1 statement2

Book page: 62

22
Example: Bi-Selection Statement
• The following test decides whether a student has passed an exam
with a pass mark of 50
if (mark >= 50)
false true
{ condition
printf("Pass\n");
} statement1 statement2
else
{
printf("Fail\n");
}
23
#include <stdio.h>

int main()
{
int a;

printf(“Please enter an interger :”);


scanf(“%d”,&a);

if (a>0) /*To test positive integer*/


{
printf(“\n You have entered positive number.”);
}

else /*if statement is FALSE*/


{
printf(“\n You have entered negative number.”);
}

return 0;
}

24
EXERCISE 2.1
(page 30 & 31)

25
Multi-Selection Statement
• Logic flow of Nested if-else Statement

26
Concept if(condition1)
{
if(condition2)
{
if(condition3)
{
statement3;
}
else
{
statement2;
}
}
else
{
statement1;
}
}
else
{
statement0;
}
27
• a multi-way decision based on several conditions is
called nested if-else.
Condition 1
if (a > b)
Condition 2 { if (a > c)
{ printf(“Biggest : a");
}
else
{ printf("Biggest : c ");
}
}
else
Condition 3
{ if (b > c)
{ printf(“Biggest : b");
}
else
{ printf("Biggest : c ");
Example }
} 28
Multi-Selection Statement
• Logic flow of if-else-if Ladder Statement

Book page: 70

29
if(condition1)
Concept statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
.
.
.
else if(condition-n)
statement-n;
else
default-statement;

30
• a multi-way decision based on several
conditions is called nested if-else.
Condition 1
if (mark >= 80)
printf("Passed: Grade A\n");
Condition 2 else if (mark >= 60)
printf("Passed: Grade B\n");
Condition 3 else if (mark >= 50)
printf("Passed: Grade C\n");
else
default-statement printf("Failed\n");

Example
31
#include <stdio.h>
int main()
int a;
printf(“Please enter an interger :”);
scanf(“%d”,&a);
if (a>0) /*To test positive integer*/
{
printf(“\n You have entered positive number.”);
}
else if (a==0) /*To test 0 value*/
{
printf(“\n You have entered zero.”)
}
else /* if statement is FALSE */
{
printf(“\n You have entered negative number.”)
}
return 0;
} 32
Example of Multiple Statements
• Having more than one statement following the if or the else, groups
together between curly brackets-compound statements.
if (mark >= 50)
{
printf("Passed\n"); printf("Congratulations\
n");
}
else
{
printf("Failed\n");
printf(“Try again!!!\n");
} 33
Switch case Statement
• Another form of the multi way decision; a well structured, but
can only be used in certain cases where;
• Only one variable is tested, all branches must depend on the value of
that variable. The variable must be an integral type. (int or char).
• Each possible value of the variable can control a single branch. A
final, catch all, default branch may optionally be used to trap all
unspecified cases.
• keyword break must be included at the end of each case statement

Book page: 67

34
Switch case Statement
• Logic flow of switch case
statement

35
Syntax
switch ( <switch variable> )
{ case <constant expression> : <statement>;[break;]
.
.
.
default : <statement>;
}

36
Example
switch (selection)
{
case 'a' : printf("Option a was selected.\n");
break;
case 'b' : printf("Option b was selected.\n");
break;
case 'c' : printf("Option c was selected.\n");
break;

default : printf("NOT A VALID CHOICE! Bye ...");


}

37
Exercise
Write a complete program with switch statement based on the
following condition:

Case d: print “Display Record”


Case m: print “Modify Record”
Case x: print “Delete Record”
Default: print “INVALID SELECTION!”

38
break;
• The break statement simply terminates the loop in which it resides.
• Syntax :
break;
• Use break within a:
• do loop
• while loop
• for loop
• switch construct

39
continue;
• Unlike break, the continue statement does not force the termination of
the loop, it simply transfer control to the beginning of the loop.
• Syntax
continue;
• Use continue within a:
• while loop
• do-while loop
• for loop

40
Example

41
EXERCISE 2.1
(page 30 & 31)

42
Loop or Repetition
• Statement executed more than 1 times
• Depend to problem’s condition
• C gives you a choice of three types of loop,
• while
• do while
• for
• Two types of repetition
• Pre-test repetition statements
• Post-test repetition statements

Book page: 74

43
While statement
• The while loop keeps repeating an action until an associated test returns
false.
• This is useful where the programmer does not know in advance how
many times the loop will be traversed.
• Syntax :
while ( <condition> )
{
<statement>
}

Book page: 75

44
While structure

45
Example: While structure
• This will print a number from 1- 10 (10 times repetition)

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

46
Exercise
• Using while control statement, write a program that
calculate the total number from 1 to 5.

47
do … while statement
• The do-while loops is similar to while loop, but the test occurs after the
loop body is executed. This ensures that the loop body is run at least once.
• Executes the specified statement until the value of the specified condition
becomes FALSE.
• Syntax
do
{
<statement>
} while ( condition );
Book page: 77

48
do-while structure

49
Example: do-while structure
• This will print a number from 1- 10
(10 times repetition)

int x=1;
do
{
printf(“ %d”,x);
x++;
} while (x<=10);
50
Exercise
• Using do-while control statement, write a program that
calculate the total number from 1 to 5.

51
For statement
• The for loop is frequently used, usually where the loop will be
traversed a fixed number of times. It is very flexible, and novice
programmers should take care not to abuse.
• Executes the specified statement as long as the condition is
TRUE.

Book page: 78

52
For Syntax
for ( [initialization] ; [test-expression] ;
[incrementation] )

• The initialization part is used to initialize any variable. This part is


performed just once at the beginning of the loop.
• The expression part determine whether the loop execution should
continue. If the value of the expression is TRUE, the statement
block will be executed, otherwise the loop will be terminated.
• The third is a statement to be run every time the loop body is
completed. This is usually an increment of the loop counter.
53
For structure

54
Example: For structure
• This will print a number from 1- 10
(10 times repetition)

int x;
for (x=1;x<=10;x++)
{
printf(“%d”,x);
}

55
Exercise
• Using for control statement, write a program that
calculate the total number from 1 to 5.

56
Pre-test & Post-test Loop
• The checking of conditions can be at the beginning or at the
end of the repetition structure.
• In a pre-test loop, the condition is checked at the beginning of
the loop.
• In a post-test loop, the conditioned is checked at the end of the
loop

Book page: 80

57
Pre-test loop (while & for loop) Post-test loop (do-while loop)
#include <stdio.h> #include <stdio.h>
int main () int main ()
{ {
int x=1; int x=1;
while (x != 1) do {
{ printf("C Programming\n");
printf("C Programming\n"); } while (x != 1);
} printf("Language\n");
printf("Language\n"); }
} Output:
Output: C Programming
Language Language

58
Event-Controlled / Condition-Controlled Loop
• This controlled loop continue looping and stop when one or
more valid values are encountered.

Book page: 81

59
#include <stdio.h>
int main ()
{
int mark;
printf("Enter a mark: ");
scanf("%d", &mark);
Output???
while (mark<0 || mark>100)
{
printf("Invalid mark! Enter new mark: ");
scanf("%d", & mark);
}

printf("Correct!");
}
60
#include <stdio.h>
int main ()
{
int mark;
printf("Enter a mark: ");
scanf("%d", &mark);

while (mark<0 || mark>100)


{
printf("Invalid mark! Enter new mark: ");
scanf("%d", & mark);
}

printf("Correct!");
}
61
Counter-Controlled
• Used to count the number of iterations (repetition of a process)
to be made. The number of iterations is already known when
entering the loop.
• The loop terminated when the maximum number of loop is
achieved.

Book page: 82

62
#include <stdio.h>
int main ()
{
int count = 0;
while (count < 5) Output???
{
printf("Hello! \n");
count = count + 1;
}
printf("Hello World!");
}
63
#include <stdio.h>
int main ()
{
int count = 0;
while (count < 5)
{
printf("Hello! \n");
count = count + 1;
}
printf("Hello World!");
}
64
Sentinel-Controlled Loop
• The loop is terminated by one specific value (Known as
sentinel). This value indicates that there is no more data to be
scanned.
• One useful sentinel in C language is the named constant EOF
(End Of File), which is defined in stdio.h header file.

Book page: 83

65
#include <stdio.h>
int main ()
{
int no;
while (no != 79) Output???
{
printf("Enter number: ");
scanf("%d", &no);
}
printf("Congratulation!");
}
66
#include <stdio.h>
int main ()
{
int no;
while (no != 79)
{
printf("Enter number: ");
scanf("%d", &no);
}
printf("Congratulation!");
}
67
Nested Loop
• All the repetition discussed so far can also be nested. (a while
loop within another while loop, a do-while loop within
another do-while loop and a for loop within another for
loop.

Book page: 84

68
int i,j,k;
Example
for(i=1;i<=6;i++)
{
for(j=1;j<=6-i;j++)
{
OUTPUT ??? printf(" ");
}
for(k=1;k<=2*i-1;k++)
{
printf("*");
}
printf("\n");
}
69
Example
Using for control statement, write a program to display the
following pattern:

*
**
***
****
*****

70
Thank You
Tips
• Writing a C program, it is best NOT to sit down at the
keyboard and start typing.
• THINK first about the program & what it is supposed to
do.
• The BEST ways: start with the overall goal & divide this
goal into several smaller tasks.

72

You might also like