Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Control Flow Structures - Conditional Control Structures

The document outlines control flow structures in the C programming language, emphasizing their importance in decision-making within programs. It covers three main types of control structures: sequence, conditional (including if, if-else, and switch statements), and repetition. Additionally, it provides examples and explanations of how these structures are implemented in C to manage program execution flow.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Control Flow Structures - Conditional Control Structures

The document outlines control flow structures in the C programming language, emphasizing their importance in decision-making within programs. It covers three main types of control structures: sequence, conditional (including if, if-else, and switch statements), and repetition. Additionally, it provides examples and explanations of how these structures are implemented in C to manage program execution flow.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1107 Principles of Programming

Control Flow Structures in C

Facilitators
Mr. Luyima Alex Cedric
aluyima@ndejjeuniversity.ac.ug
0772 302775 / 0708 045 305

Mr. Mugejjera Emmanuel


emugejjera@gmail.com
Phone: 0703 186705 / 0772 959183

Mr. Mawebe John Bosco


mawebejohnbosco@gmail.com
Phone: 0773-361111 / 0702 957911

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -1-


3 CONTROL FLOW STRUCTURES

3.1 Introduction
The order in which statements are executed in a program is called a control flow. Control structures
form the basic entities of a structured programming language. C, C++ or Java are all structured
programming languages. Control structures are used to alter the flow of execution of the program.
So, why do we need to alter the program flow?

The reason why we alter program flow is predominantly to aid “decision making“. In life, we may be
given with a set of options like doing “Electronics” or “Computer science”. We do make a decision by
analyzing certain conditions (like our personal interest, scope of job opportunities etc.). With the
decision we make, we alter the flow of our life’s direction. This is exactly what happens in a C program.
Control structures combine instructions into logical units. A Logical unit has one entry point and one
exit point.Control flow is a term routinely used in control structures. Control flow refers to the order in
which programming statements in a program are executed. There are three types of control structures
available in C
• Sequence Control Structures
• Conditional / Selection Control Structures
• Repetition Control Structures

3.2 Sequence Control Structures


Statements are executed in a top down order. No statement is skipped and no statement is executed more
than once.
For Example:
#include<stdio.h>
int main()
{
int a;
int a=5;
printf("Square of a = %d", a);
return 0;
}

3.3 Conditional Control Structures


Conditional or selection structure opts for a statement to execute on the basis of a condition. The
statement is executed when the condition is TRUE and ignored when it is FALSE e.g if, if-else,
switch structures.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -2-


Figure 4.1 Flowchart representing Selection control structures

3.3.1 The if Statement


A simple condition is expressed in the form:

if (condition)

statement;
It starts with the keyword if, followed by a condition (a logical expression) enclosed within parenthesis,
followed by the result statement.
The resulting statement is executed if the condition is evaluated as TRUE. Note that there is no semicolon
(;) after the condition expression. Consider the following example:

if (marks >50)

printf("You have passed the exam!");

If the value of the variable “marks” is greater than 50, the message “You have passed the exam!” is
displayed on the screen; otherwise the statement is skipped and no message is displayed.
/*Program 4.1 illustrates the use of if statement in a C program */
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks); //get marks
if(marks > 50) // if marks > 50 display message
printf("You have passed the exam!");
return 0;
}
Executing Program-4.1 with different inputs will behave as follows:

Case 1: Enter marks: 73


You have passed the exam!
Case 2: Enter marks: 34
Case 3: Enter marks: 50
- Ndejje University - IT 1107 / CS 1107 Principles of Programming -3-
In the second and third cases, the message “You have passed the exam!” will not be displayed.
More than one statement can be executed as a result of the condition by embedding set of statements in
a block (between two braces {}). See Program 4.2 below.

Sample Run

3.3.2 If-else Structure


The if-else structure takes the form:
if (condition)
statement- 1; else
statement- 2;
When the condition is evaluated, one of the two statements will be executed and then the program
resumes its original flow. The C language allows us to use the if-else structure in scenarios where there
is more than one outcome. You can include both the cases (TRUE and FALSE) using the if-else
structure.

Let’s take our previous example, If the value of the variable “marks” is greater than 50, the message
“You have passed the exam!” is displayed on the screen; otherwise the statement “You have failed
the exam!” is displayed.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -4-


Sample Run:

In many programs it is required to perform some action when a condition is TRUE and another action
when it is FALSE. In such cases, the if clause can be used to check the TRUE condition and act upon
it.
However, it does not act upon the FALSE condition. Therefore, the expression resulting the FALSE
condition needs to be re-organized. Hence the use of if-else structure.

3.3.3 if-else-if Ladder


In certain cases multiple conditions are to be detected. In such cases the conditions and their associated
statements can be arranged in a construct that takes the form:
if (condition-1)
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;

else
statement- n;
This construct is referred as the if-else-if ladder. The different conditions are evaluated starting from the
top of the ladder and whenever a condition is evaluated as TRUE, the corresponding statement(s) are
executed and the rest of the construct is skipped.

Example 4.1 –Write a program to display the student’s grade based on the following table:
Marks Grade

>=75 and <=100 A


> =50 and <75 B
> =25 and <50 C
< 25 and >=0 F
In this case multiple conditions are to be checked. Marks obtained by a student can only be in one of the
ranges. Therefore, if-else-if ladder can be used to implement following program.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -5-


In Program-4.6 above, when the marks are entered from the keyboard the first expression (marks >
75) is evaluated. If marks is not greater than 75, the next expression is evaluated to see whether it is
greater than 50.
If the second expression is not satisfied either, the program evaluates the third expression and so on until
it finds a TRUE condition. If it cannot find a TRUE expression statement(s) after the else keyword are
executed.
Sample Run

3.3.4 Nesting Conditions


Sometimes we need to check for multiple decisions. This can be accomplished by two approaches;
• using compound relational tests or • using nested conditions.
• When conditions are nested the if–else/ if-else-if construct may
contain other if-else/ if-else-if constructs within themselves.
In nesting you must be careful to keep track of different ifs and corresponding elses. Consider the
following example:
if (age>=15 && age<=35)
if (age<=19)
printf(“Youth and Teenager!");
else
printf(“Youth!");
An else matches with the last if in the same block. In this example the else corresponds to the second if.
Therefore, if both age>=15 && age<=35 AND age<=19 are TRUE “Youth and Teenager” will be
displayed; if (age>=15 && age<=35) is TRUE but if age<=19 is FALSE “Youth” will be displayed. If
(age>=15 && age<=35) is FALSE nothing will be displayed.
To reduce any confusion, braces can be used to simplify the source code. Therefore the above can be
rewritten as follows:

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -6-


if (age>=15 && age<=35)
{
if (age<=19)
{
printf(“Youth and Teenager!");
}
else
{
printf(“Youth!");
}
}

Example 4.2 – A car increases it velocity from u ms-1 to v ms-1 within t seconds. Write a
program to calculate the acceleration.
The relationship among acceleration (a), u, v and t can be given as
v = u + at Therefore the acceleration can be found by the
formula 𝐚 = 𝐯 −𝐮 .
𝐭
In the program we implement users to input any values for u, v and t. However, to find the correct
acceleration, the time has to be non-zero and positive (since we cannot go back in time and a number
should not be divided by zero).
So our program should make sure it accepts only the correct inputs (Time cannot be 0 or less than 0).
The Program-4.7 calculates the acceleration given u, v and t.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -7-


3.3.5 Conditional Operator
Conditional operator (?:) is one of the special operators supported by the C language. The conditional
operator evaluates an expression and returns one of two values based on whether condition is TRUE or
FALSE. It has the form:
condition ?result - 1 : result- 2;
If the condition is TRUE the expression returns result - 1 and if not it returns result - 2.

Example 4.3
Consider the following example which determines the value of variable “b” based on the whether the
given input is greater than 50 or not. If the input is greater than 50 variable “b” will be assigned “1”
and if not it will be assigned “2”.

Sample Run:
Enter value of a: 49
Value of b: 2
Conditional operator can be used to implement simple if-else constructs. However, use of conditional
operator is not recommended as a good programming practice.

3.3.6 The switch Construct


Instead of using if-else-if ladder, the switch construct can be used to handle multiple choices, such as
menu options. The syntax of the switch construct is different from if -else construct. The objective is to
check several possible constant values for an expression. It has the form:
switch (control variable )
{ case constant-1:
statement(s);
break;
case constant-2:
statement(s);
break; … case
constant-n:
statement(s);
break;
default:
statement(s);
}

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -8-


The switch construct starts with the switch keyword followed by a block which contains the different
cases. Switch evaluates the control variable and first checks if its value is equal to constant-1; if it is the
case, then it executes the statement(s) following that line until it reaches the break keyword.
When the break keyword is found no more cases will be considered and the control is transferred out
of the switch structure to next part of the program. If the value of the expression is not equal to constant-
1 it will check the value of constant-2.
If they are equal it will execute relevant statement(s). This process continuous until it finds a matching
value. If a matching value is not found among any cases, the statement(s) given after the default
keyword will be executed. The control variable of the switch must be of the type int, long or char (any
other data type is not allowed). Also note that the value we specify after case keyword must be a constant
and cannot be a variable (example: n*2).
Example 4.4: Program-4.9 can be re-written as a switch structure. See Program-4.9 below:

Switch Structure (Program 4.10 Corresponding to the program 4.9)

- Ndejje University - IT 1107 / CS 1107 Principles of Programming -9-


END

THANK YOU

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 10 -

You might also like