You are on page 1of 42

Chapter 5

CONTROL STRUCTURES IN C++

A computer program is not limited to a linear sequence


of instructions. There are times when it has to make decisions
or repeat codes. C++ has three different types of control
structures that serve to specify what has to be done by the
program, when and under which circumstances.

Three Different Types of Control Structures

1. Sequential Structure

A sequential control structure is where the statements


are executed in sequence.

Example:
n1=5 //statement 1
n2=6 //statement 2
sum = n1 + n2 //statement 3

The series of statements above will be executed in


order, where statement 1 will be executed first, then to be
followed by statement 2 and, finally, statement 3.

2. Selection Control Structure

A selection control structure (also called conditional


control structure) is used for choosing between two courses of
action. It includes the simple, two-alternative, multi-alternative
conditionals.

131
The “if” Statement

This is used to decide whether to do something at a


special point, or to decide between two courses of action. It has
three basic forms.

1. if statement

Syntax:

if (condition)
statement;

Example
if (number < 0)
cout<<“The number is negative\n";

The message “The number is negative” will be displayed


if the value of a number is less than zero. This means that the
condition is equal to true.

if condition with compound statement

The statement may either be a single statement or a


compound statement. If compound statement is used, it is
necessary to enclose it in a begin and an end brace ({ }). This is
the general form of the if condition with a compound
statement.

Syntax:

if (condition)
{
statement1;
statement2;
statement3;
statement4;

132
}

2. if-else condition

An if statement may also optionally contain a second


statement, the else clause which is to be executed if the
condition is not met.
The if-else statement is a conditional statement that
chooses one out of two alternative courses of actions.

Syntax:

if (condition)
statement1;
else
statement2;

Statement1 is executed if the condition is true, if the


condition is false statement2 will be executed.

Example:
if (num<0)
cout<<num<<”is a negative number \n”;
else
cout<<num<<”is a positive number \n”;

In the example above, if a number read is less than 0


then it would print the message “Number is a negative
number”, otherwise the message would be “Number is a
positive number”.

For if-else conditions with compound statements; the syntax is:

if (condition)
{
statement1;
statement2;

133
statement3;
}
Else
{
statement1;
statement2;
statement3;
}

If the condition is true, the statement block after the


condition will be executed. If the condition return a false value,
the statement block following else will be executed.

3. if-else-if ladder

If we want to make a multi-way decision based on


several conditions, the most general way of doing this is by
using the else if variant on the if statement. This works by
cascading several comparisons. As soon as one of these gives a
true result, the following statement or block is executed, and
no further comparisons are performed.

Syntax:

if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
:
:
else
statement;

134
The conditions are evaluated from top to bottom. As
soon as a true condition is found, the statement associated with
it is executed, and the rest of the ladder is bypassed.

If none of the conditions are true then the final else will
be executed. The final else often acts as a default condition;
that is, if all other conditional tests fail then the last else
statement is performed. If the final else is not present and all
other conditions are false, then no action will take place.

Example:
if (result >= 75)
cout<<“Passed: Grade A\n";
else if (result >= 60)
cout<<“Passed: Grade B\n";
else if (result >= 45)
cout<<“Passed: Grade C\n";
else
cout<<“Failed\n";

The above example shows the use of the if-else-if ladder


which tells us if the value currently stored in the variable result
is equivalent to a passing mark A, B, C or Failed.

Sample Problem 5-1. Draw a flowchart and write a program that


prints the remark PASSED if the input grade is greater than or
equal to 75, otherwise remark is FAILED.

Program (Sample Problem 5-1 Using if else statement)

#include<iostream>
int main()
{
int grade;
cout<<“\nEnter your grade: ";
cin>>grade;
if(grade>=75)

135
cout<<“Passed \n";
else
cout<<“Failed \n";
return 0;
}

Begin

grade=0

Print “Enter your grade: “

Read grade

Y
If
Print “PASSED”
grade>=75

Print “FAILED”

END

Figure 5-1: Flowchart (Sample Problem 5-1)

Figure 5-1a Output


(Sample Problem 5-1 Using if-else statement)

136
Figure 5-1b Output
(Sample Problem 5-1 Using if-else statement)

Program (Sample Problem 5-1 Using if-else if statement)

#include<iostream.h>
int main()
{
int grade;
cout<<“\nEnter your grade: ";
cin>>grade;
if(grade>=75)
cout<<“Passed \n";
else if (grade>=70)
cout<<“Incomplete \n";
else
cout<<“Failed \n";
return 0;
}

Figure 5-2a Output


(Sample Problem 5-1 Using if-else if statement)

137
Figure 5-2b Output
(Sample Problem 5-1 Using if-else if statement)

Figure 5-2c Output


(Sample Problem 5-1 Using if-else if statement)

Note: Compare the output in example#3-1. The remark


for the grade of 70 is FAILED, wherein in example#3-1a
for the grade of 70 the remark is INCOMPLETE.

138
Name: Section:
Instructor: Time/Day:

Laboratory Practice Task #10 – Using if-else statement


Write a program that would accept an integer number and
determine whether it is an ODD or an EVEN number.

FILENAME: PTASK10.cpp

PROGRAM

139
Sample Problem 5-2: Draw a flowchart and write a program
that will read values of a student’s grade. If the student grade is

A - Print “OUTSTANDING”
B - Print “VERY GOOD”
C - Print “GOOD”
D - Print “STUDY HARD”

Figure 5-3: Flowchart Sample Problem 5-2

140
Program (Sample Problem 5-2)

#include<iostream.h>
int main()
{
char grade;
cout<<"Enter your grade: ";
cin>>grade;
if (grade=='A')
cout<<“Outstanding \n";
else if (grade=='B')
cout<<“VERY GOOD \n ";
else if (grade=='C')
cout<<“GOOD \n ";
else if (grade=='D')
cout<<“STUDY HARD \n”;
else
cout<<“Invalid input \n";
return 0;
}

Figure 5-4a: Output (Sample Problem 5-2)

Figure 5-4b: Output (Sample Problem 5-2)

141
Figure 5-4c: Output (Sample Problem 5-2)

Sample Problem 5-3: If statement with logical operators

This program is a modified version of Example #2. It also


accepts lower case letters using the logical operator || (OR).

Program (Sample Problem 5-3)

#include<iostream.h>
int main()
{
char grade;
cout<<"Enter grade: ";
cin>>grade;
if ((grade=='A') || (grade=='a'))
cout<<”OUTSTANDING \n";
else if ((grade=='B') || (grade=='b'))
cout<<“VERY GOOD \n";
else if ((grade=='C') || (grade=='c'))
cout<<“GOOD \n";
else if ((grade=='D') || (grade=='d'))
cout<<“STUDY HARD \n";
else
cout<<“Invalid Input \n";
return 0;
}

142
Figure 5-5a: Output (Sample Problem 5-3)

Figure 5-5b: Output (Sample Problem 5-3)

143
Name: Section:
Instructor: Time/Day:

Laboratory Practice Task 11:


Using “If” statement

The XYZ Manufacturing Company plans to give year-end bonus


to its employees. Make a flowchart and write a program that
will compute for the year-end bonus of its employees
considering the following criteria:
- If employee’s monthly salary is less than or equal to
P7000, bonus is 50% of the salary.
- For employees with salaries greater than P7000, bonus is
P7000.
- Print out the names, salaries and the corresponding
bonuses of the employees.

FILENAME: PTASK11.cpp

NOTE: Please copy the correct program

144
Name: Section:
Instructor: Time/Day:

Laboratory Practice Task 12: if, if-else, if-else-if conditions

Write a program that reads in a room number, the room’s


capacity, and the size of the class enrolled so far, and prints an
output line showing the class room number, the capacity,
number of students enrolled, number of seats available, and
whether the class is closed or not.

Sample Output:
Enter room number : 426
Enter room capacity : 30
Enter no. of students enrolled : 20

Room No. Capacity Enrolled Empty Status


Students Seats
425 30 20 10 Available

FILENAME: PTASK12.cpp

NOTE: Please copy the correct program

145
Name: Section:
Instructor: Time/Day:

Laboratory Practice Task 13:

Write a program that will determine if a number is positive or


negative. If positive it should be able to display the following:

NUMBER MESSAGE
0–9 Number read is less than 10
10 Number read is 10
11 – 99 Number read is greater than 10
100 Number read is 100
101 Above Number read is greater than 100

FILENAME: PTASK13.cpp
NOTE: Please copy the correct program

146
Name: Section:
Instructor: Time/Day:

Laboratory Practice Task 14:

Write a program that solves quadratic equation of the form

ax2+bx+c=0

where a, b and c are constant coefficients. Quadratic equation


has two roots and they can be computed using the following
formulas:
root1 = -b+ b 2  4ac
2a
root2 = -b- b 2  4ac
2a

FILENAME: PTASK14.cpp

NOTE: Please copy the correct program

147
Name: Section:
Instructor: Time/Day:

Laboratory Practice Task 15:

Write a program that will determine the largest and smallest no.
of the three floating point numbers supplied by the user.

FILENAME: PTASK15.cpp

NOTE: Please copy the correct program on the space


provided.

148
The switch-case Statement

Switch is a multi-branch decision statement in C++ that


tests a list of integer and character constants. When a match is
found, a statement block is executed. The general form is:

Syntax:

switch (variable)
{
case constant1: statement sequence;
break;
case constant2: statement sequence;
break;
case constant3: statement sequence;
break;
default: statement sequence;
}

Where, the default statement is executed if no match is found.


The default is optional and, if not present, no action takes place
if all matches fail. When a match is found, the statement
associated with that case is executed until the break statement
is reached or, in the case of the default (or last case of no
default is present), the end of the switch statement is
encountered.

There are three important things to know about the switch


statement:

1. The switch differs from if in that switch can only test for
equality, whereas the if can evaluate a relational or
logical expression.

2. No two case constants in the same switch can have


identical values. Of course, a switch statement enclosed
by an outer switch may have case constants that are the
same.

149
3. If character constants are used in the switch, they are
automatically converted to their integer values.

Break – the break statement has two uses, the first one is to
terminate a case in the switch statement, while the second one
is to terminate a loop and bypass the normal loop conditional
tests. When a break statement is encountered inside the loop,
the loop is immediately terminated and the program control
resumes at the next statement following the loop.

Sample Problem 5-4: Using switch -case statement

Write a program that will ask the user to input a number


from 1 to 5 and display the number in words. If the inputted
number is outside the specified range, it must display an error
message.

Program (Sample Problem 5-4)

#include<iostream.h>
int main()
{
int num;
cout<<“input a number from 1 to 5: ”;
cin>>num;
switch (num)
{
case 1:cout<<“One”;
break;
case 2:cout<<“Two”;
break;
case 3:cout<<“Three”;
break;
case 4:cout<<“Four”;
break;
case 5:cout<<“Five”;
break;
default: cout<<“Number is out of range”;

150
}
return 0;
}

switch case that has common statements


These are switch statements that have a common
statement block but different case constants. The statement
will accept small characters and capital letters but has a
common statement.
This routine illustrates two facets of the switch
statement. First, you can have empty conditions. Second,
execution continues into the next case if no break statement is
present.

switch (ch)
{
case ‘A’: /*this has a common statement*/
case ‘a’: cout<<“Apple”;
case ‘B’:
case ‘b’: cout<<“Banana”;
case ‘C’:
case ‘c’: cout<<“Carrot”;
default:cout<<“Not an ABC character”;
}
Duplication of similar actions to several alternatives is avoided
using the switch statement. For example, the switch statement
below has duplicate actions:

switch (major_code)
{
case 1:cout<<“Science Student”;
break;
case 2:cout<<“Art Student”;
break;
case 3:cout<<“Science Student”;
break;
case 4:cout<<“Art Student”;
break;
case 5:cout<<“Science Student”;

151
}

Duplications are eliminated by arranging cases with similar


actions in groups.

switch (major_code)
{
case 1:
case 3:
case 5:
cout<<“Science Student”;
break;
case 2:
case 4:
cout<<“Art Student”;
}

152
Name: Section:
Instructor: Time/Day:

Laboratory Practice Task 16: – Using switch case statement

Create a program that would input a number in month between


1 to 12 and print the corresponding months in words, e.g.
“January”, “February”, or “December”. Furthermore, if the
month is not between 1 and 12 there should be an ERROR
message.

FILENAME: PTASK16.cpp
NOTE: Please copy the correct program

153
Name: Section:
Instructor: Time/Day:

Laboratory Practice Task 17:


switch-case statement should be used for the ff. exercises:

1. Write a program that would accept a radius of a circle and a


user’s choice of request to calculate. Compute and print the
value depending on what the user requests.

Choice Value
‘C’ or ‘c’ circumference of a circle
‘A’ or ‘a’ area of a circle
‘D’ or ‘d’ diameter of a circle

FILENAME: PTASK17a.cpp

NOTE: Please copy the correct program on the space


provided.

PROGRAM

154
2. Create a program that will ask the user to input time in a 24-
hour notation and output it in 12-hour notation. For
example, if the input is 13:45, the output should be 1:45pm.
The program should instruct the user always to enter
exactly 5 characters. So for example, nine o’clock should
output 09:00.

FILENAME: PTASK17b.cpp

NOTE: Please copy the correct program on the space


provided.

PROGRAM

155
NAME: SECTION:
INSTRUCTOR: TIME/DAY:

CASE ANALYSIS

Using integer division and modulus operator, write a program


that accepts a three-digit integer from 0 to 999 and outputs the
value in words.

Layout Screen

Input three digit number [0 – 999]: 235

The number is read as : Two hundred thirty-five

FILENAME: CSTUDY1.cpp
NOTE: Please copy the correct program on the space
provided.

156
Loops/Repetition Statements

In C++, and all other modern programming languages,


loops allow a set of instructions to be performed until a certain
condition is reached. This condition maybe predefined as in the
for loop, or open-ended as in the while and do loops.

Every programming language has a construct that can


be used to define controlled repetition (or loops) on a program
block. A program block that is executed repeatedly by a
repetition statement is called loop body. The repetition is
controlled by a condition (or predicate) that is associated with
the repetition statements:

There are two types of repetition statements:


1. Pretest repetition statements
2. Posttest repetition statements

A pretest repetition statement computes a value for its


associate predicate before entering the loop body, and will
execute the loop body as long as the predicate is true. Once the
predicate computes to false, repetition stops and the program
control pauses to the next statement that follows the
repetition statement.

Figure 5-6: Illustration of pretest repetition statement

157
On the other hand, a posttest repetition statement first
executes the loop body and then computes the predicate. If the
predicate is true, the loop body executes again; otherwise; the
repetition terminates.

In C++, the three statements for repetition are:


1. The while statement, which is a pre-test repetition
statement.
2. The for statement, which is also a pre-test repetition
statement.
3. The do-while statement, which is a post-test repetition
statement.

To display the string “Rizal Technological University”


five(5)times, you might be using the following statements
below:
cout<<“ Rizal Technological University \n”;
cout<<“ Rizal Technological University \n”;
cout<<“ Rizal Technological University \n”;
cout<<“ Rizal Technological University \n”;
cout<<“ Rizal Technological University \n”;

Imagine how tedious it would be if you want to display this line


100 times. Loops are used to solve this kind of problem.

for Statement

The for loop lets us keep performing an action over and over on
our data until a condition (which we specify) becomes true.

Syntax:
for (initialization ; condition ; increment)
statement;

The initialization is a statement that is executed when


the loop begins, often setting a loop counter to 0, condition is
the end condition, checked every time the body of the loop is
about to execute, and increment is a statement that is executed

158
at the end of the loop, just before the condition tested to see if
we should loop again.

Figure 5-7: Illustration of posttest repletion statement

Sample Problem 5-5: Using for statement

Write a program that displays the string “Rizal Technological


University” 5 times.

Program (Sample Problem 5-5)

#include <iostream.h>
int main()
{
int index;
for (index=1; index<=5;++index)
{
cout<<“Rizal Technological University \n";
}
return 0;

159
Figure 5-8: Output (Sample Problem 5-5)

Sample Problem 5-6: This program displays the string “Hello


World” ten times.

Program ( Sample Problem 5-6)

#include <iostream.h>
int main()
{
int index;
for (index=0; index<=9;++index)
{
cout<<“Hello, world \n";
}
return 0;
}

Figure 5-9: Output (Sample Problem 5-6)

160
Name: Section:
Instructor: Time/Day:

Machine Problem: Using for statement

Write a C++ program that will display the sine, cosine and
tangent values of numbers from 1-10.

FILENAME: MP6.cpp

SCREEN LAYOUT

NUMBERS SINE COSINE TANGENT


1
2
.
.
10

PROGRAM

161
while Statement

The while statement is used to control the repetition of


operations under a certain condition.

The syntax for the while statement is:

while ( Expression )
Statement
/* end while */

In this syntax, the expression enclosed in parenthesis


after the keyword while can be an arithmetic expression or a
condition expression that, when evaluated, produces a nonzero
value that corresponds to true or a zero value that corresponds
to false.

Sample Problem 5-7: Using while statement

This program displays the string “Congratulations” three times.

Program (Sample Problem 5-7)

#include<iostream.h>
int main()
{
int number;
number=0;
while (number<3)
{
cout<<“Congratulations\n";
number=number+1;
}
return 0;
}

162
Figure 5-10: Output (Sample Problem 5-7)

From Sample Problem 5-8, if expression (number<3) of


the while statement is true, then the statements enclosed in the
curly brace
{ and } are executed.

After the last statement within the curly braces


number=number+1 has been processed, control is returned to
the while expression and the condition is again evaluated. If the
condition is still true, the statements are executed again. The
loop will terminate only when the expression becomes false.
That is, the statements enclosed in the body of the while loop
are executed only while the condition is true.

The expression enclosed in the parentheses immediately


following the keyword while is called a conditional expression.
The value of a conditional expression when evaluated can only
be either true or false. The conditional expression in our
example has two operands. The first is the variable number and
the second is the decimal integer 3. The expression compares
the value of the first operand that of the second. The
comparison is performed by the less than “<” operator. For as
long as number is less than 3, the expression will return a result
of true. The while statement will terminate when number
equals 3.

163
A properly constructed while statement works as follows:

1. The expression in parenthesis is evaluated.


2. If the result of evaluation is a nonzero value (i.e., the logical
value of true), the loop body is executed. Following this,
control goes back to the expression and is evaluated again.
This continues until the expression computes to a value of
zero.
3. If the expression produces a zero value (i.e., the logical
value of false), loop body is bypassed and the program
control drops down to the statement that follows the while
statement.

Sample Problem 5-8: Using while statement

This program computes for the sum of two numbers and uses
while statement to ask if you want to continue.

#include<iostream.h>
int main()

{
int num1,num2,sum;
char more='Y';
while (more=='Y' || more== 'y')
{/*begin while*/
cout<<“Enter 1st number: ";
cin>>num1;
cout<<“Enter 2nd number:";
cin>>num2;
sum=num1+num2;
cout<<“The sum is "<<sum<<“\n";
cout<<“Do you want to continue[y/n]";
cin>>more;
}/*end while */
return 0;
}

164
Figure 5-11 Output (Sample Problem 5-8)

165
Name: Section:
Instructor: Time/Day:

Machine Problem: – Using while

Write a program that would ask the user to enter positive float
values from the keyboard when prompted by the program. To
signal end of input the user enters a negative integer. When
data entry has terminated, the program should output the
following:
a) minimum value entered
b) maximum value entered
c) Average of the positive values entered.
If there is no data entry, (the user enters a negative number
initially) then the program should output a message indicating
that no data has been entered.

FILENAME: MP7.cpp
NOTE: Please copy the correct program on the space
provided.

PROGRAM

166
The do-while loop

Unlike the for and while loops, which test the loop
condition at the top of the loop, the do-while loop checks its
condition and the bottom of the loop. This means that a do-
while loop will always execute at least once.

The syntax for the do-while loop is:

do
{
statement;
}
while(condition);

Although the braces are not necessary when only one


statement is present, they are usually used to improve
readability and avoid confusion with the while.

Sample Problem 5-9: Using do-while

This program uses a do-while loop to read numbers from the


keyboard until one is less than 100:

Program (Sample Problem 5-9)

#include<iostream.h>
int main()
{
int num;
do
{
cin>>num;
}
while(num>100);
return 0;
}

167
Figure 5-12 Output (Sample Problem 5-9)

Sample Problem 5-10: Using “do-while” and “if” statement

Here is an example of the use of a do-while loop. The following


program is a game that allows a user to guess a number
between 1 and 100. A do-while loop is appropriate since we
know that winning the game always requires at least one guess.

Program (Sample Problem 5-10)

#include <iostream.h>
int main()
{
int number = 44;
int guess;
cout<<“Guess a number between 1 and 100\n";
do {
cout<<"Enter your guess: ";
cin>>guess;

if (guess > number)


cout<<"Too high\n";
if (guess < number)
cout<<"Too low\n";
} while (guess != number);
cout<<“You win. The answer is "<<number;
return 0;
}

168
Figure 5-13 Output (Sample Problem 5-10)

Perhaps the most common use of the do-while loop is in


a menu-selection routine. Because you will always want a menu-
selection routine to execute at least once, the do-while loop is
an obvious choice. By testing for a valid response at the bottom
of the loop, you can re-prompt the user until a valid response is
entered. The following program fragment shows how to add a
do-while loop onto the menu for the four basic operations
program.
do
{

cout<< “Choose an operation ”;


cout<< “[1] Addition \n”;
cout<< “[2] Subtraction \n”;
cout<< “[3] Multiplication \n”;
cout<< “[4] Division \n”;
cout<< “Enter your choice: ”;
cin>>choice;

} while(choice<1 || choice>4);

After the options have been displayed, the program will loop
until a valid option is selected. Loops can also be nested.

169
Name: Section:
Instructor: Time/Day:

Machine Problems: Loops


1. Write a program that will read in a number, n, and then
output the sum of the squares of the numbers from 1 to
n. So if the input is 3, the output should be 14, because:

12+22+32=1+4+9=14

FILENAME: MP8.cpp

Screen Layout

Input a number : _____

The sum of the square of the number is :

2. Design a program that will get the factorial (n!) of an


inputted number.

FILENAME: MP9.cpp

Screen Layout

Input a number : _____

The factorial value is :

NOTE: Please copy the correct program

170
3. Write a program that computes for the square, the
square root and the fourth power of numbers from 0 to
25. Display the numbers using a neat four-column format
as shown below:

FILENAME: MP10.cpp

Screen Layout

NUMBER SQUARE SQUARE ROOT FOURTH POWER


0 0 0 0

25

4. Create a program that displays a 10x10 multiplication


table.

FILENAME: MP11.cpp

5. Some banks make debtors pay in round, yearly amounts.


Make a program that would input a loaned amount
(must be positive), the annual interest rate, and the
annual payment, and would output the schedule of
payment as illustrated below:
Ex. Loan is P800.00, rate is 10% and payment is 200.00

Schedule of payments would be as follows:

Screen Layout:

LOAN : 800.00
RATE : 10%
PAYMENT : 200.00

171
YEAR PRINCIPAL INTEREST PAYMENT
1 800 80 200
2 680 68 200
3 548 54.80 200
4 402.80 40.28 200
5 243.08 24.308 200
6 67.388 6.7388 74.1268

FILENAME: MP12.cpp
NOTE: Please copy the correct program

172

You might also like