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

Chapter Six-Control Structures in C

Computer

Uploaded by

Anthony
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Chapter Six-Control Structures in C

Computer

Uploaded by

Anthony
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

MAT 224-Introduction to Data Processing and Computers

Chapter Six: Control structures in C on which control structure can be used to achieve a given task
appropriately.
6.1 Introduction
6.2 Control structures in C
In most of the programs presented above, the statements have
There are two broad categories of control structures in namely
been sequential, executed in the order they appear in the main
 Decision control structures which include control structures
program. Control Statements are meant to control the logic of
program's execution i.e. the order in which the instructions in a such as if statements, if ...Else statements , if…else if…else
program must be executed. They make it possible to make and switch statement
decisions, to perform tasks repeatedly or to jump from one  Iterative/Looping/Repetitive control structures which
section of code to another. Just like other programming enables a section of a program to be executed repeatedly
languages, C supports a number of control structures. until a given condition has been met or for a specified
number of times. C supports three loop constructs i.e. do...
While Loop, while loop and the for loop
Programmers may need to test values of variables and
depending on the result, alternative statements may be 6.3 Decision control structures
executed. This facility can be used to select among alternative This type of control structure uses a Boolean expression
courses of action. It can also be used to build loops for the (true/false). Statements are only executed if a condition is true
repetition of basic actions. else the statement is skipped. The Boolean expression is
usually constructed using relational operators and logical
operator
This chapter therefore aims at familiarizing the learners to C
C programming language provides following types of decision
control structures. The chapter also aims at providing insights
control structures.
1
1|CHAPTER SIX:-CONTROL STRUCTURES
CMT 110: PROGRAMMING METHODOLOGY

 If statements printf("Enter three numbers: "); scanf("%f %f %f",

 If else statement &a, &b, &c);

 If…else if…else statements


if(a>=b && a>=c)
 Switch case statement
printf("Largest number = %.2f", a);
4.3.1 The If selection control statement if(b>=a && b>=c)
It’s the simplest and most common selection structure printf("Largest number = %.2f", b);
consisting of a Boolean expression followed by one or more if(c>=a && c>=b)
statements. Its general syntax is as follows printf("Largest number = %.2f", c);

if (condition) }

{ 4.3.2 The If…else selection control statement


Statements; It’s used to carry out a logical test and then take one of two
} possible actions depending on the outcome of the test (i.e.,

The statements within the if shall only be executed if the whether the outcome is true or false).The general syntax is as

condition evaluates to true else the statement is skipped. A follows

good example is a program to calculate the largest number out If (condition)


of three numbers entered from the keyboard using the if only {

/* C program to find largest number using if statement only */ Statement ;


Void main() }
{ else
float a, b, c; {

2|CHAPTER FOUR:-CONTROL STRUCTURES


CMT 110: PROGRAMMING METHODOLOGY

Statement ; int num;


} printf(" Enter a number:\n");
First the condition is evaluated. If the condition specified in the scanf("%d", &num);
if statement evaluates to true, then statements inside the if- if(num>0)
block are executed and then the control gets transferred to the {
statement immediately after the if-block. Even if the condition is printf( "n The number %d is positive.",num);
false and no else-block is present, control gets transferred to }
the statement immediately after the if-block. else
{
printf("n The number %d is negative.",num);
The else part is required only if a certain sequence of
}
instructions needs to be executed if the condition evaluates to
Another example which makes use of if…else statement is
false. It is important to note that the condition is always
specified in parentheses and that it is a good practice to enclose presented below. Let’s look at the following section code for a

the statements in the if blocks or in the else-block in braces, program which is supposed to calculate the roots of a quadratic
equation
whether it is a single statement or a compound statement.
A good example is presented below. It’s a program to
determine if the user has read a negative or positive number
from the keyboard

/*program to find if a number is negative or not */


void main( )
{

3|CHAPTER FOUR:-CONTROL STRUCTURES


CMT 110: PROGRAMMING METHODOLOGY

// testing for real solutions to a quadratic Variable real_roots is of type bool assigned the value true in

d = b*b - 4*a*c; one of the branches and false in the other.

if(d >= 0.0)


{ Another example is presented below. It’s a program for
// real solutions calculating the largest number out of three numbers entered
root1 = (-b + sqrt (d)) / (2.0*a); from the keyboard using the if ...else statement
root2 = (-b - sqrt (d)) / (2.0*a); void main( )
real_roots = true; {
} float a, b, c;
else printf("Enter three numbers: ");
{ scanf("%f %f %f", &a, &b, &c);
// complex solutions real = -b / (2.0*a); if (a>=b)
imaginary = sqrt (-d) / (2.0*a); {
real_roots = false; if(a>=c)
} printf("Largest number = %.2f",a);
else
If the previous example, if the Boolean condition is true, i.e. printf("Largest number = %.2f",c);
(d >= 0), then the program calculates the roots of the }
quadratics two real numbers. Else (If the Boolean condition else
is false), then a different path is initiated i.e. the program {
calculates the real and imaginary parts of the complex roots. if(b>=c)

4|CHAPTER FOUR:-CONTROL STRUCTURES


CMT 110: PROGRAMMING METHODOLOGY

printf("Largest number = %.2f",b); else if (condition-n)


else {
printf("Largest number = %.2f",c); statement;
} }
} else

4.3.3 If…else if…else selection statement {

While making decisions in any programming language, it’s statement;

possible to have a variable that has more than two possibilities. }

In this scenario, it will be possible to use one if or else if We shall rewrite the program for determining the largest number
statement inside another if or else if statement(s). This can be out of three integers numbers entered from the keyboard using
done by placing if statements within other if-else constructions. if…else if…else

if (condition-1) 4.3.4 Switch statement in C

{ Rather than using multiple if/else statements, C also provides a

statement; special control structure; switch which allows a variable to be


tested .The expression been switched should be of either
}
integer data type for equality against a list of values. Its general
else if (condition-2)
syntax is as follows.
{
statement; switch (expression)
}. {
… case constant 1:
… statements;

5|CHAPTER FOUR:-CONTROL STRUCTURES


CMT 110: PROGRAMMING METHODOLOGY

break; would be evaluated. In case you forget to put in one of the break

case constant 2: statements, then execution can continue from one case

statements; statement into another.

break;
…… The different between a switch control structure and the others
…… is that braces are not required around multiple statements.

……. 6.4 Repetitive/iterative control structures in C


case constant-n: In the previous article on control statements we discussed the
statements; decision-making statement i.e. if-else and the selection
break; statement switch-case. In this section we will continue the
default: discussion on control statements and discuss the iteration

statement; statements.

}
Iterative control structures allow statement (s) to be executed

The expression being switched needs to e of type integer. This repeatedly until a certain condition is met and or a specified

means we can successfully switch an int or a char data number of times. Just like other programming languages, C

type. programming language provides different types of


iterative/repetitive control structures known as loops which
The value of the expression can be a variable and not a
handle looping requirements.
constant. Break statement causes the program to terminate the
 While loop
switch after execution of one choice otherwise the next case
 Do while loop

6|CHAPTER FOUR:-CONTROL STRUCTURES


CMT 110: PROGRAMMING METHODOLOGY

 For loop scanf("%d",&n);

4.4.1 The WHILE loop in C i=0;

This type of loop iterates statement (s) provided a given while(i<n)

condition is true. It tests the condition before executing the loop {


body. Its general syntax is as follows printf("\nEnter the value of integer

while (condition) %d then press enter key " ,i+1);


scanf("%i",&numbers);
{
if (numbers%2==0)
statements;
{
} sum=sum+numbers;
evennum=evennum+1;
The condition is tested first and if it’s true, the statements
}
enclosed by the curly braces are executed repeatedly. Once the
i++;
condition turns to false, the loop terminates. The program
}
control is then transferred to the first line after the closing brace.
avg=sum/evennum;
You can have as many statements as you like inside the loop,
including one or zero. If at all the condition (Boolean printf("The sum of %d numbers is % d and

expression) is initially false the statements are not executed. their average is %d",evennum,sum,avg);
}
Void main( )
{ 4.4.2 The do…while loop in C

Int i,n,evennum=0,numbers,avg=0,sum=0; This type of loop just like the while loop iterates statement (s)

printf("how many numbers do you want to enter?"); provided a given condition is true. However, the condition is

7|CHAPTER FOUR:-CONTROL STRUCTURES


CMT 110: PROGRAMMING METHODOLOGY

usually tested at the end of the loop after executing the block of void main()
statements at least once .Its general syntax is as follows {

do inti,n,evennum=0,numbers,avg=0,sum=0;
printf("how many numbers do you want to enter?");
{
scanf("%d",&n);
//statements to be executed;
i=0;
}
do
while(condition);
{
printf("\nEnter the value of integer %d then press enter key " ,i+1);
Note the semicolon which ends the do…while statement. The scanf("%i",&numbers);
difference between while and do…while is that the while loop if (numbers%2==0)
will first test the condition at the beginning of the loop and will {

not execute even a single once if the condition is false, whereas sum=sum+numbers;

the do…while loop tests the condition at the end of the loop after evennum=evennum+1;
}
completing the first iteration.
i++;
While loop is widely used in many applications as it is more
}
natural to test for the continuation of a loop at the beginning
while (i<n);
rather than at the end of the loop.
avg=sum/evennum;
Most programs that work with while can also be implemented printf("The sum of %d numbers is % d and
using do…while. The following program calculates the sum of their average is %d",evennum,sum,avg);
digits in the same manner, except that it uses the do-while loop: }

8|CHAPTER FOUR:-CONTROL STRUCTURES


CMT 110: PROGRAMMING METHODOLOGY

The do…while statement should be used only in situations  Termination expression, which represents a condition
where the loop must execute at least once whether or not the that must be true for the loop to continue execution.
condition is true. For example, we can use a do…while loop  Step-value expression is executed after every iteration
while designing an interactive menu-driven program where the to update the value of the looping value. The for
menu is presented at least once, and then depending upon the statement is very versatile and can be written in four
choice of the user, the menu is displayed again or the session different ways:
is terminated. Omitting the Initialization Expression
4.4.3 The For statement In this case, the loop variable is initialized before the for loop.
For loop statement executes statements repeatedly for a Thus, the for loop takes the following form:
specified number of times. Its syntax is as follows. i=0;/*initialization*/
for(initialization; termination; step-value) for(; condition;step-value)
{ {
Statements to be executed //statements to be executed
} }

The components of the for loop consists of three expressions:


 Initialization expression, which initializes the loop The semicolon that terminates the initialization expression is
variable. The loop variable controls the looping action. present before the condition expression.
The initialization expression is executed only once, when Omitting the Condition
the loop begins. In this case the condition is specified inside the body of the for
loop, generally using an if statement.

9|CHAPTER FOUR:-CONTROL STRUCTURES


CMT 110: PROGRAMMING METHODOLOGY

The while or do-while statements may also be used to specify 6.5 Chapter summary
the condition. Thus the for loop takes the following form: 6.6 Chapter exercise
for (initialization; ; step-value) 1. Write a C program which output odd numbers and their
{ squares in a tabular format. The even numbers being
condition //statements to be executed calculated range from 3 to 15
} No Square

gain, it can be seen that the semicolon that terminates the 3 6

condition is present in the for statement. 5 25

Omitting the step-value Expression 7 49

In this case the step-value expression is written inside the body 2. Write a C program which calculates the roots of a quadratic

of the for loop. equation whose formulae is as follows

Omitting all Three Expressions


It is also possible to omit all three expressions, but they should
Additional information
be present in the ways discussed above. If all three expressions
are omitted entirely i.e., they are not mentioned in the ways The Discriminant is calculated as b2-4ac and three things
discussed above then the for loop becomes an infinite or never- can happen to the discriminant
ending loop. In this case, the for loop takes the following form:  If the Discriminant >0 the we have two roots
for (;;)  If the Discriminant >0 then we no real roots
{
 If the Discriminant =0 then we only one root
//statements
3. Write a C program which accepts three integers from the
}
keyboard and return the largest out of the three

10 | C H A P T E R F O U R : - C O N T R O L S T R U C T U R E S

You might also like