0% found this document useful (0 votes)
496 views

UNIT 3: Program Control Structures

The document discusses program control structures and introduces selection structures using if and if-else statements. It explains that control structures allow altering the sequential flow of a program's execution. Selection structures use conditional statements like if and if-else to perform certain tasks depending on whether a conditional expression evaluates to true or false. Examples are provided to demonstrate how if and if-else statements work.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
496 views

UNIT 3: Program Control Structures

The document discusses program control structures and introduces selection structures using if and if-else statements. It explains that control structures allow altering the sequential flow of a program's execution. Selection structures use conditional statements like if and if-else to perform certain tasks depending on whether a conditional expression evaluates to true or false. Examples are provided to demonstrate how if and if-else statements work.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

UNIT 3 : Program Control Structures

UNIT

3 PROGRAM CONTROL
STRUCTURES

This lesson introduces control structures to


provide alternatives to sequential program
execution. Control structures are used to alter the
sequential flow of execution. A computer can
process a program in one of the following ways:
in sequence; selectively, by making a choice,
which is also called a branch; repetitively, by
executing a statement in a certain number of
times based on some conditions.

IT 103: COMPUTER PROGRAMMING 1 118


UNIT 3 : Program Control Structures

PRETEST

WHAT DO YOU ALREADY KNOW?

Name: __________________________________ Date: ____________________


Course & Section: ________________________ Result: __________________

TRUE OR FALSE. Write T if the statement is true, if not, write F.

________ 1. C++ supports two types of conditional statements: if and switch


statements.
________ 2. The if statement is used when the program is made to choose one
statement.
________ 3. The use of braces is required where only a single statement
appears in an if statement .
________ 4. The if-else statement is used when the program is made to
choose one of the two paths or statements.
________ 5. A conditional expression is Boolean expression that evaluates to
a true or false value.
________ 6. Relational operators are used in switch statement.
________ 7. Initialization is the last part of a loop structure
________ 8. If the counter variable is smaller than or equal to the maximum
value, the loop will be terminated.
________ 9. A for statement is a count-controlled loop.
________ 10. A do-while loop is useful for programs that want to loop at least
once.

IT 103: COMPUTER PROGRAMMING 1 119


UNIT 3 : Program Control Structures
1. C++ fully supports object-oriented programming including the four pillars of object-oriented
development.

LESSON 1:
Selection Structure:
The if /if - else Statement

OBJECTIVES:
At the end of the lesson, students will be able to:

 Learn about control structures

 Discover how to create selection control structures

 Apply the use of if/if-else statements

DURATION: 9 hours

IT 103: COMPUTER PROGRAMMING 1 120


UNIT 3 : Program Control Structures

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.

Conditional statements are features of programming language to construct a


selection structure. These are statements used to perform a certain task which depend
on whether the conditional expression specified evaluates to true or false.

C++ supports two types of conditional statements: if and switch statements.

The if Statement

if- statement (one-way selection)

The if statement is used when the program is made to choose one statement.

True True

Condition Condition

statement Statement1

False
False

Statement2

The general form of if statement is:

if (conditional expression)
statement;

IT 103: COMPUTER PROGRAMMING 1 121


UNIT 3 : Program Control Structures

where:

conditional expression is Boolean expression that evaluates to a TRUE OR


FALSE value.

statement any single C++ statement

Consider the given program segments below.

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;

IT 103: COMPUTER PROGRAMMING 1 122


UNIT 3 : Program Control Structures

Example 4 :

x=4;
Output
if (x>=5)
x*=2; 6
x+=2;
cout<< x;

if- statement with a block of statements

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;
}

IT 103: COMPUTER PROGRAMMING 1 123


UNIT 3 : Program Control Structures

Consider the given program segment below.

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;

IT 103: COMPUTER PROGRAMMING 1 124


UNIT 3 : Program Control Structures

Example 7 :

x=4; Output
if (x>=5)
{
x*=2; 4
x+=2;
}
cout<< x ;

Example 8 :

A program that determines if the grade inputted is a passing grade. The


passing grade is 75.

#include <iostream> #include <iostream>


using namespace std; using namespace std;

int grade; int grade;


int main() int main()
{ {
cout<<“ENTER GRADE:”; cout<<“ENTER GRADE:”;
cin>> grade; cin>> grade;
if (grade>=75) if (grade>=75) with braces

cout<< grade << PASSED”; {


cout<< grade << PASSED”;
return 0; }
} return 0;
}

IT 103: COMPUTER PROGRAMMING 1 125


UNIT 3 : Program Control Structures

The if – else Statement

if – else statement (two-way selection)

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

The general form of if-else statement is:

if (conditional expression)
statement 1;
else
statement 2;

IT 103: COMPUTER PROGRAMMING 1 126


UNIT 3 : Program Control Structures

if- else statement with block of statements

if (conditional expression)
{
statement(s);
}
else {
statement(s);
}

where:

conditional expression is boolean expression that evaluates to a TRUE or FALSE


value

statement(s) may either be a single statement or a block of statements

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”;

IT 103: COMPUTER PROGRAMMING 1 127


UNIT 3 : Program Control Structures

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 ;

IT 103: COMPUTER PROGRAMMING 1 128


UNIT 3 : Program Control Structures

Example 5 :

x=6; Output
if (x<=5)
{
x+=2;
} 13
else
{
x*=2;
x++;
}
cout<< x ;

Example 6 :

A program that determines if a number is even or odd.

#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

IT 103: COMPUTER PROGRAMMING 1 129


UNIT 3 : Program Control Structures

Example 6 :

A program that determines if the student passed or failed the subject based
on the entered grade.

#include <iostream> #include <iostream>


using namespace std; using namespace std;

int grade; int grade;


int main() int main()
{ {
cout<<“Student Grade: ”; cout<<“Student Grade: ”;
cin>> grade; cin>> grade;
if (grade>=75) if (grade>=75)
cout<<“PASSED”; { with braces

else cout<<“PASSED”;
cout<<“FAILED”; }
return 0; else
} {
cout<<“FAILED”;
}
return 0;
}

Sample Output

Student Grade: 80 Student Grade: 74


PASSED FAILED

IT 103: COMPUTER PROGRAMMING 1 130


UNIT 3 : Program Control Structures

Ladderized if-else Statement


The ladderized if-else statement used to is used if there are three or more
possible outcomes are expected in a program

True
Condition 1
Statement 1

False

True

Condition 2
Statement 2

False

Statement 3

End

The general form of the if-else-if ladder statement is:

if (conditional expression_1)
statement_1;
else if (conditional expression _2)
statement_2;
else if (conditional expression _n)
statement_n;
:
:
else
statement_else;

IT 103: COMPUTER PROGRAMMING 1 131


UNIT 3 : Program Control Structures

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.

IT 103: COMPUTER PROGRAMMING 1 132


UNIT 3 : Program Control Structures

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

IT 103: COMPUTER PROGRAMMING 1 133


UNIT 3 : Program Control Structures

Example 2 :

A program that computes the bonus of an employee based on the salary.


Salary Bonus
greater than 10000 60% of salary
less than 10000 40% of salary
equal to 10000 50% of salary

#include <iostream>
using namespace std;

double salary, bonus;

int main()
{
cout<<"Salary : ";
cin>>salary;
if (salary >10000)
{
bonus = salary *.60;
}
else if (salary <10000)
{
bonus = salary *.40;
}
else
{
bonus = salary *.50;
}

cout<<” Bonus :”<< bonus;

return 0;
}

Sample Output

Salary : 10000
Bonus : 5000

IT 103: COMPUTER PROGRAMMING 1 134


UNIT 3 : Program Control Structures

The Nested if / if-else Statement


The nested if/ if-else statement is known as nested when there is another if/if-
else statement inside it. This is considered a sub-condition of a parent condition.

False True
Condition
1

Statement 2
False Condition
1.1

Statement 1.1
True

Statement 1.2

The general form of the nested if-else statement is:

if ( conditional expression_1)
{
if ( conditional expression_1.1)
{
statement_1.1;
}
else
{
statement_1.2;
}
}
else
{
statement_2;
}

 If conditional_expression_1 is true, conditional_expression_1.1 will then be


tested; otherwise, it will proceed to statement_2.
 If condition_expression1.1 is true, statement 1.1 is to be executed; otherwise,
proceed to statement 1.2.

In a nested condition, indention is important as it helps to figure out individual


constructs and makes the program easy to read.

IT 103: COMPUTER PROGRAMMING 1 135


UNIT 3 : Program Control Structures

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

IT 103: COMPUTER PROGRAMMING 1 136


UNIT 3 : Program Control Structures

APPLICATION ACTIVITY FOR LESSON 1

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

Trace the output of each program segment.


1.
x=6;y=10; Output
if (x<=5)
{
y+=2;
}
else
{
y++;
}
cout<< y ;

2.
x=6;y=10; z=0; Output
if (y + x > 10)
{
z = x + 5;
}
else
{
z = y + 10;
}
cout<< z ;

IT 103: COMPUTER PROGRAMMING 1 137


UNIT 3 : Program Control Structures

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 ;

IT 103: COMPUTER PROGRAMMING 1 138


UNIT 3 : Program Control Structures

APPLICATION ACTIVITY FOR LESSON 1

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Create a program that will determine if the inputted number is a positive, negative or
zero.

IT 103: COMPUTER PROGRAMMING 1 139


UNIT 3 : Program Control Structures

APPLICATION ACTIVITY FOR LESSON 1

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

Create a program that determines the amount of discount based on the product code
entered by the user.

Product Code Price Discount Rate


A 450.00 5%
B 850.00 10%

IT 103: COMPUTER PROGRAMMING 1 140


UNIT 3 : Program Control Structures

APPLICATION ACTIVITY FOR LESSON 1

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

Create a program that that determines the amount of discount based on the product
code and product no. entered by the user.

Product Code Product No. Price Discount Rate


A 1 450.00 5%
2 850.00 10%
B 1 300.00 3%
2 700.00 6%

IT 103: COMPUTER PROGRAMMING 1 141


UNIT 3 : Program Control Structures
1. C++ fully supports object-oriented programming including the four pillars of object-oriented
development.

LESSON 2:
Selection Structure:
The switch Statement

OBJECTIVES:
At the end of the lesson, students will be able to:

 Learn about control structures

 Discover how to create selection control structures

 Apply the use of switch statement

DURATION: 5 hours

IT 103: COMPUTER PROGRAMMING 1 142


UNIT 3 : Program Control Structures

The switch Statement


The switch statement is a multi-way decision and used when there are multiple
conditions. It is an alternative statement for an if-else ladder with a limitation that switch
can only test for equality.

The general form of the switch statement is:

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.

IT 103: COMPUTER PROGRAMMING 1 143


UNIT 3 : Program Control Structures

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;

cout<< “ Color Code: “;


switch(glevel)
{
case 7:{
cout<<"YELLOW";
break;
}
case 8:{
cout<<"RED";
break;
}
case 9:{
cout<<"GREEN";
break;
}
case 10:{
cout<<” BLUE”;
break;
}
default:{
cout<<”NOT PART OF JUNIOR HIGH SCHOOL”;
}
}//end of switch

return 0;
}

Sample Output

Grade Level: 8
Color Code : RED

IT 103: COMPUTER PROGRAMMING 1 144


UNIT 3 : Program Control Structures

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

IT 103: COMPUTER PROGRAMMING 1 145


UNIT 3 : Program Control Structures

Sample Output

First Number : 8
Second Number : 8

MATHEMATICAL OPERATION
[A]ddition
[S]ubtraction
[M]ultiplication
[D]ivision

Enter your choice: 1

SUM : 16

IT 103: COMPUTER PROGRAMMING 1 146


UNIT 3 : Program Control Structures

APPLICATION ACTIVITY FOR LESSON 2

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

Create a program that will perform each task for a rectangle based on the menu
selected by the user.

Menu

[1] Area
[2] Perimeter

Area of rectangle = length * width


Perimeter of rectangle = 2 * length + 2 * width

IT 103: COMPUTER PROGRAMMING 1 147


UNIT 3 : Program Control Structures

APPLICATION ACTIVITY FOR LESSON 2

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

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

Sub-menu of Area Sub-menu of Perimeter


[1] Circle [1] Triangle
[2] Square [2] Rectangle

Area of circle = 3.14 * radius* radius

Area of square = side *side

Perimeter of triangle = side 1 + side 2 + side 3

Perimeter of rectangle = 2 * length + 2 * width

IT 103: COMPUTER PROGRAMMING 1 148


UNIT 3 : Program Control Structures

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:

 Learn about repetition(looping) structures

 Discover how to create repetitive program structure

 Apply appropriate statements in creating for loop structures

DURATION: 10 hours

IT 103: COMPUTER PROGRAMMING 1 149


UNIT 3 : Program Control Structures

Repetitive Control Structure

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.

 Iterative statements (loops) are among the most common programming


structures. It is necessary because algorithms also need to repeat those
segments over and over again.

 Iterative statements (loops) allow a set of instructions to be repeated or


carried out several times until certain conditions have been met. It can be
predefined as in the for loop, or open-ended as in while and do-while.

 The looping statement is a program statement that repeats a statement or


sequence of statements in a given number of times.

Condition-Controlled and Count-Controlled Loops

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.

IT 103: COMPUTER PROGRAMMING 1 150


UNIT 3 : Program Control Structures

The FOR statement

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.

The general form of the for statement is:

for(initialization; condition; increment)


{
statement_sequence;
}

IT 103: COMPUTER PROGRAMMING 1 151


UNIT 3 : Program Control Structures

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 :

A program that will print “HELLO” five times.

#include <iostream>
using namespace std;
int x;
main() {

for(x=1; x<=5; x++)


cout<< “HELLO\n”;

return 0;
}

IT 103: COMPUTER PROGRAMMING 1 152


UNIT 3 : Program Control Structures

Sample Output

HELLO
HELLO
HELLO
HELLO
HELLO

Example 3 :

A program that will print the numbers 1 to 10.

#include <iostream>
using namespace std;
int x;
main() {

for(x=1; x<=10; x++)


cout<< x<<" ";
return 0;
}

Sample Output

1 2 3 4 5 6 7 8 9 10

IT 103: COMPUTER PROGRAMMING 1 153


UNIT 3 : Program Control Structures

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 :

A program that will output the sum of 1 to 10.

#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

IT 103: COMPUTER PROGRAMMING 1 154


UNIT 3 : Program Control Structures

Tracing Output:
What would be the expected output of the given program segments?

Example 5 :

for( int g=12; g<=21;g=g+6)


Output
{
cout<<“\nHello World\n;
}

Example 6 :

for( int j= 0; j<5; j=j+1)


Output
{
cout<<“\n HELLO ”;
}

Example 7 :

for( int r = 5; r<=20; r =r+5)


Output
{
sum= sum + r;
}
cout<<“The result is ”<<sum;
Program No. 3 Output:

IT 103: COMPUTER PROGRAMMING 1 155


UNIT 3 : Program Control Structures

NESTED for loop


In the nested for loop, the inner loop is executed first before returning to the main
loop and checking the condition again.
The general form of the nested for loop statement is:

for (initialization; condition1; increment1)


{

for (initialization; condition2; increment2)

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;
}

IT 103: COMPUTER PROGRAMMING 1 156


UNIT 3 : Program Control Structures

Sample Output
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3

Example 2 :

A program that will create a 10 x 10 multiplication table.

# 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;
}

IT 103: COMPUTER PROGRAMMING 1 157


UNIT 3 : Program Control Structures

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 ( x=1; x<=5; x++)


Output

{
for ( y=1; y<=3;y++)
{
cout<<“HELLO\n”;
}
cout<<“THANK YOU!\n”;
}

IT 103: COMPUTER PROGRAMMING 1 158


UNIT 3 : Program Control Structures

Example 4 :

for ( x=1;x<=8;x=x+2)
Output
{
for ( y=0;y<5;y=y++)
{
z= x+y;
}

cout<<z<<endl;
}

IT 103: COMPUTER PROGRAMMING 1 159


UNIT 3 : Program Control Structures

APPLICATION ACTIVITY FOR LESSON 3

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Trace the following program. What would the expected output be? Write the answer in the box given.
Program No. 1

Output:

IT 103: COMPUTER PROGRAMMING 1 160


UNIT 3 : Program Control Structures

Program No. 2

Output:

Program No. 3

Output:

IT 103: COMPUTER PROGRAMMING 1 161


UNIT 3 : Program Control Structures

Program No. 4

Output:

IT 103: COMPUTER PROGRAMMING 1 162


UNIT 3 : Program Control Structures

Program No. 5

Output:

IT 103: COMPUTER PROGRAMMING 1 163


UNIT 3 : Program Control Structures

HOW DO YOU EXTEND YOUR


LEARNING?
ASSIGNMENT/ LEARNING INSIGHT/REFLECTION

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________
1. Encode and run the following codes.

WRITE THE OUTPUT ON THE BOX BELOW.

2. Encode and run the following codes.

IT 103: COMPUTER PROGRAMMING 1 164


UNIT 3 : Program Control Structures

WRITE THE OUTPUT ON THE BOX BELOW.

3. Encode and run the following codes.

WRITE THREE SAMPLE DIALOGUE HERE.

IT 103: COMPUTER PROGRAMMING 1 165


UNIT 3 : Program Control Structures

4. Encode and run the following codes.

5. WRITE THE OUTPUT ON THE BOX BELOW.

IT 103: COMPUTER PROGRAMMING 1 166


UNIT 3 : Program Control Structures

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:

 Learn about while and do…while statement structures

 Discover how to create repetitive program structure using while


and do…while

 Apply relevant statements when designing and creating


programs using while loops.

DURATION: 6 hours

IT 103: COMPUTER PROGRAMMING 1 167


UNIT 3 : Program Control Structures

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.

The general form of the while statement is:

while(condition)
{
statement_sequence;
}

where:

condition is a relational /bolean expression that determines when the loop


will exit

statement_sequence can be either a single statement or a series of


statements that make up the loop structure.

IT 103: COMPUTER PROGRAMMING 1 168


UNIT 3 : Program Control Structures

Example 1 :

A program that will print the numbers 1 to 10

#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

IT 103: COMPUTER PROGRAMMING 1 169


UNIT 3 : Program Control Structures

Example 2 :

A program that will print the sum of 1 to 10.

#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

IT 103: COMPUTER PROGRAMMING 1 170


UNIT 3 : Program Control Structures

Tracing the Output:

What would be the output of the given program segments?

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;

IT 103: COMPUTER PROGRAMMING 1 171


UNIT 3 : Program Control Structures

Example 5:

int y=10, x=5;


Output
while (x<20)
{
if (y%2==0)
{
x=x+y;
cout<< x<<”\n”;
}
y++;
}

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);

IT 103: COMPUTER PROGRAMMING 1 172


UNIT 3 : Program Control Structures

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

Enter series of integers until 0 is entered:

Enter the number: 27

Enter the number: 12

Enter the number: 0

The sum is 39

IT 103: COMPUTER PROGRAMMING 1 173


UNIT 3 : Program Control Structures

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

The factorial value: 120

IT 103: COMPUTER PROGRAMMING 1 174


UNIT 3 : Program Control Structures

APPLICATION ACTIVITY FOR LESSON 3

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Directions: Trace the following program. What would the expected output be? Write the answer in the
box given.
Program No. 1

Output:

IT 103: COMPUTER PROGRAMMING 1 175


UNIT 3 : Program Control Structures

Program No. 2

Output:

Program No. 3

Output:

IT 103: COMPUTER PROGRAMMING 1 176


UNIT 3 : Program Control Structures

HOW DO YOU EXTEND YOUR


LEARNING?
ASSIGNMENT/ LEARNING INSIGHT/REFLECTION

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________
Encode and run the following code using code blocks.

WRITE THE OUTPUT ON THE BOX BELOW.

IT 103: COMPUTER PROGRAMMING 1 177


UNIT 3 : Program Control Structures

6. Encode and run the following code using code blocks.

WRITE THE OUTPUT ON THE BOX BELOW.

IT 103: COMPUTER PROGRAMMING 1 178


UNIT 3 : Program Control Structures

GRADING RUBRICS FOR UNIT 3

HOW DID YOU PERFORM?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

HANDS-ON ACTIVITY RUBRIC

CATEGORY 21-25 11-20 6-10 0-5

86 – 100 61 – 85 percent 31 – 60 percent


percent followed the followed the No Program
Program
followed the Program Program Structure
Structure
Program Structure Structure
Structure

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

Finished the Did not finished


Finished exactly 10 minutes
work/project the actual work
Finished Time with the allotted below, finished
before the with the allotted
time given the allotted time
allotted time time given

86 - 100 10 – 35 percent
61 - 85 percent 36 - 60 percent
Output percent No correct
correct output correct output
correct output output

IT 103: COMPUTER PROGRAMMING 1 179


UNIT 3 : Program Control Structures

POST-TEST FOR UNIT 3

HOW MUCH HAVE YOU LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Read each item carefully, then circle the letter that best represent your answer

1. How do you write a conditional statement for executing some code if


“i” is equal to 5?
a. if (i=5) then
b. if (i=5);
c. if (i=5)
d. if (i==5) then

2. How does a for loop start?


a. for(x=0; x<=100; x+=5)
b. for(x=0, x<=100, x+=5)
c. for(x=0; x<=100; x+=5);
d. for(x=0, x<=100, x+=5);

3. How does a do…while loop should be written?


a. do {
cout<<x <<(“hello world!”)<<endl;
x+=5;}
while (x<=15);

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;

IT 103: COMPUTER PROGRAMMING 1 180


UNIT 3 : Program Control Structures

4. The line code: x+=5 is also the same as _________.


a. x=x+x+x+x+x
b. x=x+5
c. x=x*x
d. none of the above

5. Each repetition of a loop is called _____.


a. Cycle
b. Orbit
c. Revolution
d. Iteration

6. The while loop is a _____ type of loop.


a. Pretest
b. Post test
c. Prequalified
d. Post iterative

7. The do-while loop is a _____ type of loop


a. Pretest
b. Post test
c. Prequalified
d. Post iterative

8. A section in a switch statement is branched to if none of the


case values match the expression listed after the select
statement.
a. Else
b. If
c. If-else
d. Default

9. What is the output of the following program?


#include<iostream>
#include <cstdlib>
using namespace std;
int main()
{int x=50, sum=0;
do{
cout<<x<<(“\t”)<<sum<<endl;
sum+=x;
x-=10;}
while (x<50);}

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

IT 103: COMPUTER PROGRAMMING 1 182

You might also like