You are on page 1of 50

Chapter 4

Control Statement
Objectives
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
Overview
Statements fall into three general types;
Assignment, where values, usually the results of
calculations, are stored in variables.
Input / Output, data is read in or printed out.
Control, the program makes a decision about what to do
next.
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 developed – run time
Sequential Control Statement
One way directly from top to bottom

#include <stdio.h>
start
void main()
input
{ Basic salary
allowances
float
b_sal,allw,T_inc; Total income = basic salary
+ allowances
scanf(“%f”,&b_sal);
scanf(“%f”,&allw); Print total
income
T_inc = b_sal+allw;
end
printf(“%f”,T_inc);
}
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
Bi-Selection
Multi-Selection
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.
Single-Selection Statement
Logic flow of if … statement

true
condition

false
statement2
Example
It is possible to use the if part without the else.

if (temperature < 0)
printf("Frozen\n");
Bi-Selection Statement
Logic flow of if … else statement

false true
condition

statement1 statement2
Example
The following test decides whether a student has
passed an exam with a pass mark of 50
if (mark >= 50)
printf("Pass\n");
else
printf("Fail\n");
Multi-Selection Statement
Logic flow of Nested if-else Statement
Concept
if(condition1)
{
if(condition2)
{
if(condition3)
statement3;
else
statement2;
}
else
statement1;
}
else
statement0;
Example
a multi-way decision based on several conditions
is called nested if-else.

if (a > b)
if (a > c)
printf(“Biggest : a");
else
printf("Biggest : c ");
else
if (b > c)
printf(“Biggest : b");
else
printf("Biggest : c ");
Multi-Selection Statement
Logic flow of if-else-if Ladder Statement
Concept
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
.
.
.
else if(condition-n)
statement-n;
else
default-statement;
Example
a multi-way decision based on several conditions
is called nested if-else.
if (mark >= 80)
printf("Passed: Grade A\n");
else if (mark >= 60)
printf("Passed: Grade B\n");
else if (mark >= 50)
printf("Passed: Grade C\n");
else
printf("Failed\n");
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");
}
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.
Switch case Statement
Logic flow of switch case statement
Syntax
switch ( <switch variable> )
{ case <constant expression> : <statement>;
[break;]
.
.
.
default : <statement>;
}
Example
switch (selection) {
case 'a' : printf("\nOption a was selected.\n");
break;

case 'b' : printf("\nOption b was selected.\n");


break;
case 'c' : printf("\nOption c was selected.\n");
break;
default : printf("\nNOT A VALID CHOICE! Bye ...");
}
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!”
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
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
Example
int i,sum=0;
for (i=1; i<10; i++)
{
if(i%2) continue;
sum=sum+i;
printf("\n%d",sum);
}

The above loop totals up the even numbers 2, 4, 6, 8


and stores the value in variable sum.
If the expression i%2 yields a non-zero value, the
continue statement is executed.
If the remainder is zero, sum= sum + i is executed
and next loop iteration is started.
goto
Use the goto statement to transfer control to the
location of a local label specified by <identifier>.
Labels are always terminated by a colon.
Syntax:
goto <identifier> ;
Example
int sum=0,i=1,data;
next: i++;
printf("Enter the number: ");
scanf("%d",&data);
sum+=data;
if(i<5) goto next; //Control pass to next
if i < 5 printf("\nSum= %d",sum);

If i is less than 5, goto transfer the control to the


statement with next:
goto
It is recommended that don’t use the goto statement.
This because if used frequently, the program will be
difficult to understand and debug.
Use goto when the program want to exit from a deeply
nested loop.
Loop or Repetition
Statement executed more than 1 times
Depend to problem’s condition
Two types
Pre-test repetition statements
Post-test repetition statements

C gives you a choice of three types of loop,


while
do while
for
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>
}
While structure
Example
This will print a number from 1- 10 (10 times
repetition)

int x=1;
while (x<=10)
{
printf(“ %d\n”,x);
x++;
}
Exercise
Using while control statement, write a program that
calculate the total number from 1 to 5.
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 );
do-while structure
Example
This will print a number from 1- 10 (10 times
repetition)

int x=1;
do
{
printf(“ %d”,x);
x++;
} while (x<=10);
Exercise
Using do-while control statement, write a program
that calculate the total number from 1 to 5.
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.
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.
for structure
Example
This will print a number from 1- 10 (10 times
repetition)

int x;
for (x=1;x<=10;x++)
{
printf(“%d”,x);
}
Exercise
Using for control statement, write a program that
calculate the total number from 1 to 5.
Example
The initial value (s) in the initialization part
doesn’t have to be zero and the incrementation
value doesn’t have to be 1.

int x;
for (x=2;x<=10;x=x+2)
{ printf(“%d”,x);
}
Exercise
Using a control statement, write a program that
calculate the total number from 1 to 5.
What is the difference between while, do-while and
for ?
Infinite loops
The infinite or never-ending loop can be created using
for(;;) or while(1).
When using infinite loops, be sure to provide an exit
from loop using either break or return statement.
Example
int selection;

for (;;)
{
printf("\nMenu\n");
printf("\n1-Add Record");
printf("\n2-Delete Record");
printf("\n3-Exit");

printf("\n\nEnter your selection: ");


scanf("%d",&selection);

if (selection==3) break; //or return 0


}
Nested Loops
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.
Example
int i,j;

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

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

You might also like