UNIT 3: Program Control Structures
UNIT 3: Program Control Structures
UNIT
3 PROGRAM CONTROL
STRUCTURES
PRETEST
LESSON 1:
Selection Structure:
The if /if - else Statement
OBJECTIVES:
At the end of the lesson, students will be able to:
DURATION: 9 hours
Selection Structure
We have learned from the previous lesson that the execution of instructions by
selection is wherein conditions for a series of alternative statements are evaluated to
specify which instruction is to be executed.
The if Statement
The if statement is used when the program is made to choose one statement.
True True
Condition Condition
statement Statement1
False
False
Statement2
if (conditional expression)
statement;
where:
Example 1 :
x=5;
Output
if(x>=5)
cout<<“hello”;
hello good day
cout<<“good day”;
Example 2 :
x=4;
Output
if(x>=5)
cout<<“hello”;
good day
cout<<“good day”;
Example 3 :
x=5;
Output
if (x>=5)
x*=2; 12
x+=2;
cout<< x;
Example 4 :
x=4;
Output
if (x>=5)
x*=2; 6
x+=2;
cout<< x;
The use of braces in an if statement with a single statement is optional but required
when code contains a block of statements. Writing braces, whether single or block of
statements, is recommended as it makes the code more readable and helps avoid
errors when modifying a program.
if (conditional expression)
{
Statement1;
.
.
.
Statement n;
}
Example 5 :
x=5;
Output
if (x>=5)
{ hello good day
cout<<“hello ”;
cout<<“good day”;
}
Example 6 :
x=4;
Output
if (x>=5)
{
cout<< “hello ”; God Bless
cout<< “good day”;
}
cout<< “God Bless”;
Example 7 :
x=5;
Output
if (x>=5)
{
10
x*=2;
10
cout<< x <<endl ;
}
cout<< x <<endl;
Example 7 :
x=4; Output
if (x>=5)
{
x*=2; 4
x+=2;
}
cout<< x ;
Example 8 :
The if- else statement is used when the program is made to choose one of the two
paths or statements.
True
condition Statement1
False
Statement2
End
if (conditional expression)
statement 1;
else
statement 2;
if (conditional expression)
{
statement(s);
}
else {
statement(s);
}
where:
In an if-else statement, the statement or block of statements after the if statement will
be executed if the expression is evaluated to TRUE; otherwise, the statement or block
of statements in the else statement will be executed.
Example 1 :
x=5;
Output
if(x>=5)
cout<<“hello”;
hello
else
cout<<“good day”;
Example 2 :
x=5;
Output
if(x<5)
cout<<“hello”;
good day
else
cout<<“good day”;
Example 3 :
x=4; Output
if (x>=5)
x*=2;
else 4
x+=2;
cout<< x ;
Example 4 :
x=6; Output
if (x>=5)
{
x+=2;
} 8
else
{
x*=2;
}
cout<< x ;
Example 5 :
x=6; Output
if (x<=5)
{
x+=2;
} 13
else
{
x*=2;
x++;
}
cout<< x ;
Example 6 :
#include <iostream>
using namespace std;
int number;
int main()
{
cout<<"Enter a Number : ";
cin>>number;
if(number%2==0)
cout<<"\n It is an EVEN number";
else
cout<<"\n It is an ODD number"
return 0;
}
Sample Output
Enter a Number : 8 Enter a Number : 7
It is an EVEN number It is an ODD number
Example 6 :
A program that determines if the student passed or failed the subject based
on the entered grade.
else cout<<“PASSED”;
cout<<“FAILED”; }
return 0; else
} {
cout<<“FAILED”;
}
return 0;
}
Sample Output
True
Condition 1
Statement 1
False
True
Condition 2
Statement 2
False
Statement 3
End
if (conditional expression_1)
statement_1;
else if (conditional expression _2)
statement_2;
else if (conditional expression _n)
statement_n;
:
:
else
statement_else;
if ( conditional expression_1)
{
statement_1;
}
else if (conditional expression _2)
{
statement_2;
{
else if (conditional expression _n)
{
statement_n;
}
:
else
statement_else;
In a ladderized if-else statement, the expressions are evaluated from the top
to the last condition. As soon as one of the conditions is satisfied or evaluates to
TRUE, the statements associated with it is executed, and the remaining conditions will
not be executed. If all other conditions are false, the last else statement is executed.
If the final else is not present, then no action takes place.
Example 1 :
A program that accepts a numerical grade as input, then displays the character grade
as output, based on the given grade:
Range Equivalent Grade
90 and above A
80 – 89 B
70 – 79 C
60 – 69 D
below 60 E
# include <iostream>
using namespace std;
int grade;
main()
{
cout<<"\n ENTER GRADE:";
cin>>grade;
if ((grade>=90) && (grade <=100))
cout<<"\n Your equivalent Grade is A";
else if ((grade >= 80 ) && (grade <=89))
cout<<"\n Your equivalent Grade is B";
else if ((grade >= 70 ) && (grade <=79))
cout<<"\n Your equivalent Grade is C";
else if ((grade >= 60) && (grade <=69))
cout<<"\n Your equivalent Grade is D";
else
cout<<"\nYour equivalent Grade is E";
return 0;
}
Sample Output
ENTER GRADE: 95
Your equivalent Grade is A
Example 2 :
#include <iostream>
using namespace std;
int main()
{
cout<<"Salary : ";
cin>>salary;
if (salary >10000)
{
bonus = salary *.60;
}
else if (salary <10000)
{
bonus = salary *.40;
}
else
{
bonus = salary *.50;
}
return 0;
}
Sample Output
Salary : 10000
Bonus : 5000
False True
Condition
1
Statement 2
False Condition
1.1
Statement 1.1
True
Statement 1.2
if ( conditional expression_1)
{
if ( conditional expression_1.1)
{
statement_1.1;
}
else
{
statement_1.2;
}
}
else
{
statement_2;
}
Example :
A program that only accepts even number then checks if it is greater than 10 or not.
#include <iostream>
using namespace std;
int number
int main()
{
cout<<"Enter a Number : ";
cin>>number;
if (number %2==0)
{
if ( number >10)
{
cout<<” The number is even and greater than 10”;
}
else
{
cout<<” The number is even but not greater than 10”;
else
{
cout<<” Invalid Input”;
}
return 0;
}
Sample Output
Enter a Number : 8
The number is even but not greater than 10
2.
x=6;y=10; z=0; Output
if (y + x > 10)
{
z = x + 5;
}
else
{
z = y + 10;
}
cout<< z ;
3.
x=4;y=10; Output
if (x<=5)
{ if (y<10)
y+=2;
}
else
{
y++;
}
cout<< y ;
4.
x=6;y=10;z=0; Output
if (x<10)
{
if (y>10)
{
z+=2;
}
else
{
z+=4;
}
z+=6;
}
else
{
z = y + 10;
}
cout<< z ;
Create a program that will determine if the inputted number is a positive, negative or
zero.
Create a program that determines the amount of discount based on the product code
entered by the user.
Create a program that that determines the amount of discount based on the product
code and product no. entered by the user.
LESSON 2:
Selection Structure:
The switch Statement
OBJECTIVES:
At the end of the lesson, students will be able to:
DURATION: 5 hours
switch ( variable_expression)
{
case constant1:{
statement sequence_1;
break;
}
case constant2: {
statement sequence _2;
break;
}
case constant3: {
statement sequence _3;
break;
}
default: {
statement sequence _3;
break;
}
}
It evaluates the variable (with integer or character data type) whether it matches
one of the case constants (integer or character values), then based on the outcome,
it executes the corresponding case. The default segment of the switch is executed if
no matches are found.
The break statement is used to terminate/exit, the statement sequence associated
with each case constant. Whenever this statement is encountered, the execution
directly comes out of the switch and ignoring the rest of the given cases.
Just like if statement, nesting of switch statements are allowed, which means you can
have switch statements inside another switch.
Example 1:
A program that determines the color code of Junior High School students based on
the grade level.
#include <iostream>
using namespace std;
int glevel;
int main()
{
cout<<"Grade Level : ";
cin>>glevel;
return 0;
}
Sample Output
Grade Level: 8
Color Code : RED
Example 2:
A program that allows the user to enter two numbers and select what particular
mathematical operation he wants to apply.
# include <iostream>
using namespace std;
char operation;
int num1,num2,operation, answer;
main()
{
cout<<"First Number : ";
cin>>num1;
cout<<"Second Number : ";
cin>>num2;
cout<<”MATHEMATICAL OPERATION”
cout<<"[ A ]ddition\n";
cout<<"[ S ]ubtraction\n";
cout<<"[ M ]ultiplication\n";
cout<<"[ D ]ivision"; cout<<endl;
cout<<” Enter your choice:”;
cin>>operation;
switch(operation)
{
case 'A':{
answer = num1 + num2 ;
cout<<" SUM : "<< answer;
break;
}
case 'S': {
answer = num1 + num2 ;
cout<<"DIFFERENCE: "<< answer;
break;
}
case 'M': {
answer = num1 + num2 ;
cout<<"PRODUCT:"<<answer;
break;
}
case 'D': {
answer = num1 + num2 ;
cout<<"QUOTIENT : "<<answer;
break;
}
default: {
cout<<"You have entered an invalid option “;
break;
}
}//end of switch
return 0;
} //end of program
Sample Output
First Number : 8
Second Number : 8
MATHEMATICAL OPERATION
[A]ddition
[S]ubtraction
[M]ultiplication
[D]ivision
SUM : 16
Create a program that will perform each task for a rectangle based on the menu
selected by the user.
Menu
[1] Area
[2] Perimeter
Create a program that will perform each task based on the menu selected by the
user. Combine if and switch statements.
Main Menu
[1] Area
[2] Perimeter
1.
2. C++ fully supports object-oriented programming including the four pillars of object-oriented
development.
LESSON 3:
Repetitive Structure :
The for Statement
OBJECTIVES:
At the end of the lesson, students will be able to:
DURATION: 10 hours
Instead of writing the same sequence structure that includes a lot of duplicated code,
the best way to execute the process repeatedly is to write the code in a structure that
allows repeat it several times as possible, this repetition structure is more commonly
known as a loop or iterative statement.
The way the count-controlled loop works is simple: the loop holds a count of the
number of times it runs, and the loop stops when the count reaches the specified
amount. A count-controlled loop uses a variable known as a counter variable, or
simply a clock, to store the number of iterations it has made.
The loop normally performs the following three actions: initialization, test, and
increment:
1. Initialization: The counter variable is initialized to the starting value before
the loop starts. The starting value that is used depends on the situation.
2. Test: The loop checks the counter-variable by adding it to the maximum
value. If the counter variable is smaller than or equal to the maximum value,
the loop will iterate. If the counter variable is smaller than or equal to the
maximum value, the loop will iterate. If the counter is higher than the
maximum value, the program exits the loop.
3. Increment: To increase a variable implies to increase its value. For each
iteration, the loop will add 1 to the counter variable.
Assume that the counter variable is an integer variable in the flowchart. The first step
is to assign the corresponding starting value to the counter. Then decide whether the
counter is less than or equal to the maximum value. If this is valid, the loop body will
execute it. Otherwise, the program will leave the loop. Note that one or more
statements are executed in the loop body, and then 1 is added to the counter.
The for statement or for loop is known to be a predefined loop because the
number of times it executes on its body is fixed in the context of the loop.
The for loop has a counter whose values determine the number of times the
loop will iterate. The iteration stops executing upon reaching the number of
times specified in the loop.
where:
initialization is a declaration of assignment used to set the loop counter.
condition is a Boolean relational expression that specifies when the loop will
exit.
increment determines how the loop counter can alter each time the loop is
repeated.
statement_sequence can be a single Turbo C statement of a series of Turbo
C statements that make up the loop structure.
The for loop will continue executing until the condition is Valid. If FALSE
has been completed, the program execution will restart on the statement
following the for loop.
Note:
(a) Never put a semi-colon right after the for header. It is a logical mistake.
b) Never alter the value of the loop counter within the loop structure. This
would have an effect on the result of the program.
c) After the first iteration of the loop, the increment portion of the for loop is
executed.
Example 1 :
#include <iostream>
using namespace std;
int x;
main() {
return 0;
}
Sample Output
HELLO
HELLO
HELLO
HELLO
HELLO
Example 3 :
#include <iostream>
using namespace std;
int x;
main() {
Sample Output
1 2 3 4 5 6 7 8 9 10
In the above example, the counter of the for loop is x with the initial value of 1.
After initialization, the control of the program proceeds to the condition to test whether
the value of x is within the limit (less than or equal to 10). If the result of the conditional
expression is TRUE, then it will execute the body of the loop, that is, printing the value
of x.
After the first iteration of the loop, the value of x will be incremented, making its
value equal to 2. The control of the program will go back again to the condition part to
determine if the result is TRUE or FALSE. Since the condition is evaluated as TRUE,
the value of x will again be printed; then, the increment part will be performed again.
The process continues until the value of x meets its limit or the conditional expression
evaluates to FALSE.
Example 4 :
#include <iostream>
using namespace std;
int num;
int sum;
main()
{
for(num=1; num<=10; num++)
{
sum=sum + num;
}
cout<< "\nThe Sum of 1 to 10 is "<<
sum;
return 0;
}
Sample Output
The sum of 1 to 10 is 55
Tracing Output:
What would be the expected output of the given program segments?
Example 5 :
Example 6 :
Example 7 :
statement(s);
Example 1 :
# include <iostream>
using namespace std;
int num1,num2;
main()
{
for (num2=0;num2<=1;num2++)
{
for(num=0;num1<=3;num1++)
{
cout<<num2<<” “<<num1<<endl;
}
}
return 0;
}
Sample Output
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
Example 2 :
# include <iostream>
using namespace std;
int row,column,table;
main()
{
for (column=1;column<=10;column++)
{
for(row=1;row<=10;row++)
{
table=row*column;
cout<<table <<" \t" ;
}
}
return 0;
}
Sample Output
1 2 3 4 5 6 7 8 9 10
2 4 8 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 56 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 56 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Tracing Output:
What would be the expected output of the given program segments?
Example 3 :
{
for ( y=1; y<=3;y++)
{
cout<<“HELLO\n”;
}
cout<<“THANK YOU!\n”;
}
Example 4 :
for ( x=1;x<=8;x=x+2)
Output
{
for ( y=0;y<5;y=y++)
{
z= x+y;
}
cout<<z<<endl;
}
Trace the following program. What would the expected output be? Write the answer in the box given.
Program No. 1
Output:
Program No. 2
Output:
Program No. 3
Output:
Program No. 4
Output:
Program No. 5
Output:
1.
2. C++ fully supports object-oriented programming including the four pillars of object-oriented
development.
LESSON 4:
Repetitive Structure :
The while and do-while Statements
OBJECTIVES:
At the end of the lesson, students will be able to:
DURATION: 6 hours
while loop
The while loop gets its name from the way it works: while a condition is true, do
some task. This loop statement has two parts: (1) a condition that is tested for a true
or false value, and (2) a statement or set of statements that is repeated as long as the
condition is true.
The diamond symbol is the state that is being checked. Note what happens if
the condition is true: one or more statements are executed, and the execution of
the program flows back to the point just above the diamond symbol. The condition
is evaluated again, and if it is valid, the process repeats itself. If the condition is
evaluated to false, then the program will exit the loop.
while(condition)
{
statement_sequence;
}
where:
Example 1 :
#include <iostream>
using namespace std;
int x ;
main()
{
x=1;
while (x<=10)
{
cout<<x<< "\t";
x++;
}
return 0;
}
Sample Output
1 2 3 4 5 6 7 8 9 10
Note:
For while loops that will execute multiple statements, braces are needed
Example 2 :
#include <iostream>
using namespace std;
main()
{
int num=1,sum=0;
while (num<=10)
{
sum=sum + num;
num=num + 1;
}
cout<< "\nThe Sum of 1 to 10 is " << sum;
return 0;
}
Sample Output
The sum of 1 to 10 is 55
Example 3:
int g=1;
Output
int sum=0;
while(g<=5)
{
sum=sum + g;
g++;
}
cout<<”The sum is” <<sum;
Example 4:
int r=1;
Output
while(r<=5)
{
cout<<r;
r++;
}
cout<<”The sum is” <<sum;
Example 5:
do...while loop
Do...while is like a ‘while’ statement, except that it tests the condition at the
end of the loop body. DO..WHILE loops are applicable, if the task needs to perform
at least once.
The general form of the while statement is:
do {
statement_sequence;
while (condition);
Example 1 :
A program prompts the user to enter series of integers which will be terminated
when 0 is entered and will display the sum of all the integer values entered.
# include <iostream>
using namespace std;
int a, sum=0;
main()
{
cout<<"\n Enter the series of integers, until 0 is
entered \n ";
sum = 0;
do
{
cout<<"\n Enter the number: \n ";
cin>> a;
sum=sum+a;
}
while (a!=0 );
cout<<"\n The sum is" << sum;
return 0;
}
Sample Output
The sum is 39
Example 2 :
A program that computes the factorial value of n ( as input ) and displays it.
# include <iostream>
using namespace std;
int n,f=0, i;
main ()
{
cout<<"\nEnter a Number\t";
cin>>n;
f=1;
i=n;
do
{
f=f*i;
i--;
}
while (i>= 1);
cout<<"\nThe factorial value: "<<f;
return 0;
}
Sample Output
Enter a Number 5
Directions: Trace the following program. What would the expected output be? Write the answer in the
box given.
Program No. 1
Output:
Program No. 2
Output:
Program No. 3
Output:
Followed the
Seemingly Did not follow
Required Followed the format but
followed the the required
Format required format changed the
required format format
other item
86 - 100 10 – 35 percent
61 - 85 percent 36 - 60 percent
Output percent No correct
correct output correct output
correct output output
Read each item carefully, then circle the letter that best represent your answer
b. do {
cout>>x >>(“hello world!”)>>endl;
x+=5;}
while (x<=15);
c. do {
cout<<x <<(“hello world!”)<<endl
x+=5}
while (x<=15)
d. do
cout<<x <<(“hello world!”)<<endl;
x+=5;
while x<=15;
a. 0 0
b. 0 50
c. 50 0
d. 50 50
10. What is the output that will be produced when you run the
following program:
#include<iostream>
IT 103: COMPUTER PROGRAMMING 1 181
UNIT 3 : Program Control Structures
#include<cstdlib>
using namespace std;
int main()
{ int p;
do {
cout <<p<<(“\tI Love Programming!”)<<endl;
p-=50;
} while (p>=150);}
a. 50 I Love Programming!
b. 0 I Love Programming!
c. 0 I Love Programming!
50 I Love Programming!
100 I Love Programming!
150 I Love Programming!
d. None of the above