0% found this document useful (0 votes)
208 views23 pages

Unit 5

The document discusses three types of logical structures in programming: 1. Sequence structure - Instructions are executed line by line from top to bottom. 2. Selection structure - Allows non-sequential execution based on comparisons. Includes if, if-else, and switch statements. 3. Repetition structure - Allows instructions to be executed repeatedly based on a condition. Details if, if-else statements and nested conditional logic.

Uploaded by

ijaisa77
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
208 views23 pages

Unit 5

The document discusses three types of logical structures in programming: 1. Sequence structure - Instructions are executed line by line from top to bottom. 2. Selection structure - Allows non-sequential execution based on comparisons. Includes if, if-else, and switch statements. 3. Repetition structure - Allows instructions to be executed repeatedly based on a condition. Details if, if-else statements and nested conditional logic.

Uploaded by

ijaisa77
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 23

E3062/5/1

Logical Structure Types And Basic Instruction

UNIT 5

Logical Structures And Basic Instructions

OBJECTIVES

General Objective : To Understand the logical structure types and basic instruction
refers to the order of execution of instructions in program.

Specific Objectives : At the end of the unit you will be able to :

 describe the sequence structure


 describe the selection structure
 describe the Repetition structure
 execute instructions sequentially or line by line
 explain the program control structures
 write the simple program using program control structure
E3062/5/2

Logical Structure Types And Basic Instruction

INPUT

5.0 Introduction To Logical Structure

Logical structure or program control structures refer to the order of execution of


instructions in a program. So far, in all our examples, the instructions were executed
sequentially one by one, from the top downwards. However, most real life problems
require some kind of decision making, which involves comparing values, and based
on the comparison, to take a certain course of action. Hence, C++ provides structure
that will allow the non-sequential execution of program instructions. This means that
an instruction or a whole block of instructions can be executed, repeated or skipped.

5.1 Logical Structures And Basic Instructions

C++ has a set of rich and powerful control structures (statements) that makes it a
popular language. Control structure generally fall into four categories but in this unit
we have to know only three of them, which are:
i. sequence structure
ii. selection structure
iii. repetition or iteration structure
E3062/5/3

Logical Structure Types And Basic Instruction

5.1.1 Sequence structure

The sequence control structure is the simplest of all the structures. The
program instructions are executed one by one, starting from the first
instruction and ending in the last instruction as in the program segment.

Example :
x = 5 (S1)
y = 10 (S2)
Total = x * y (S3)
cout<< “ \n ” << “Total =” <<Total<< “\n”; (S4)

Entry
Exit
S1 S2 S3 S4

Figure 5.1 : The sequence structure


(Ref. C++ Through Examples-PSellapan)

5.1.2 Selection Structure

The selection structure allows to be executed non-sequentially. It allows the


comparison of two expressions, and based on the comparison, to select a
certain course of action. In C++ , there are three types of selection
statements. They are:
a. if statement
b. if-else statement
c. Switch statement.

a. if Statement

The basic form of the if statement is:

If (expression) statement
E3062/5/4

Logical Structure Types And Basic Instruction

In this form, the expression is first evaluated. If the expression


evaluates to non-zero (meaning TRUE), the statement is executed; if
it evaluates to zero (meaning FALSE), the statement following the if
statement is executed. Again, it has one entry point and one exit point.

x >10 No

Yes

Print x

Figure 5.2 : If - Statement


(Ref. C++ Through Examples-PSellapan)

Example 5.1:

If ( gred == ‘A’ )
cout<< “\n PASS ” ;

Example 5.2:

#include<iostream.h>
main()
{
int iVar1;
int iVar2;

iVar1 =20;
iVar2 =10;

if (iVar1 > iVar2)


cout << iVar1 << “is greater than” <<iVar2;
}
E3062/5/5

Logical Structure Types And Basic Instruction

The if statement checks to see if iVar1 is greater than iVar2. If iVar


is greater than iVar2 (which is true in this case), then the instruction is
executed and the output below is achieved.

20 is greater then 5

b. if – else statement

The basic form of the if-else statement is :

if (expression) statement_1, else statement_2

In this form, the expression is first evaluated. If it evaluates to non-


zero, statement_1 is executed, otherwise (i.e, if it evaluates to zero)
statement_2 is executed. The execution of the statements are mutually
exclusive, meaning, either statement_1 is executed or statement_2,
but not both. The statement can, of course, take the form of blocks.

x >10? No

Yes Increment
x by 1
Print x

Figure 5.3 : If – else Statement


(Ref. C++ Through Examples-PSellapan)
E3062/5/6

Logical Structure Types And Basic Instruction

Example 5.3:
if ( gred == ‘ E ’ )
cout<< “\n FAIL ” ;
else
cout<< “\n PASS ” ;

Example 5.4:

#include<iostream.h>
main()
{
int iNum;

cout << “Enter a Number” ;


cin >> iNum;
if (iNum !=0) && (iNum%2) == 0)
{
cout << “Even Number”;
}
else
{
cout << “Odd Number or Number is 0” ;
}
}

The if – else statement in the Example5.4 is to checks the value of


iNum to be not equals to zero and also that the modulus value of the variable
iNum is equal to zero. If condition is true, then the message ‘Even Number’
is printed on the screen. If condition is not true, then the message ‘Odd
Number or Number is 0’ is printed on screen.
E3062/5/7

Logical Structure Types And Basic Instruction

i. nested if – else statement

The basic form of the if-else statement is :

if (expression_1)
if (expression_2)
if (expression_3)
statement_1;
else
statement_2;
else
statement_3;
else
statement_4;

In this nested form, expression_1 is evaluated. If it is zero,


statement_4 is executed and the entire nested if statement is terminated; if
not, control goes to the second if and expression_2 is evaluated. If it is zero,
statement_3 is executed; if not, control goes to the third if and expression_3
is evaluated. If it is zero, statement_2 is executed; if not, statement_1 is
executed.
Example 5.5
If (sex = ‘M’
{
if (age <=12)
{
cout << “Good Day Master”;
}
else
cout << “Good Day Mister”;
}
else if (sex = ‘F’)
{
if (age <= 12)
{
cout << “Good Day Miss”;
}
else
cout << “Good Day Madam”;
}
E3062/5/8

Logical Structure Types And Basic Instruction

In the program, Example 5.5 there are multiplies if statements


used to evaluate the sex of a person whether the person is a male or
female. Then, it is further tested on the age of the person to decide on
the title used to address the person.

c. Switch statement

The switch statement is the multiple branch decision statement


is sometimes called the multiple-choice statement. The general form
of the switch statement is :

Switch (expression)
{
Case constant_1;
Statement sequence;
break;
case constant_2;
statement sequence;
break;
.
.
default :
statement sequence;
}

The expression evaluates to an integer or character constants


and statement sequence is a block of statements.

Expression
x=?

x=1 x=2 default


y=x+1 y=x+2 y=x

Figure 5.4 : Switch Statement(Ref. C++ Through Examples-PSellapan)


E3062/5/9

Logical Structure Types And Basic Instruction

Example 5.6

#include<iostream.h>
main()
{
char cGrade;

cout << “Please key in grade (A-F) : ” ;


cin >> cGrade;

switch (cGrade)
{
case ‘A’
cout << “Minimun marks is 80” <<endl;
break;
case ‘B’:
cout << “Minimun marks is 60” <<endl;
break;
case ‘C’
cout << “Minimun marks is 40” << endl;
break;
case ‘D’:
cout << “Minimun marks is 25” << endl;
break;
default :
cout<< “Marks between 0-24” <<endl;
}

The sample output of the program:

Please key in grade (A-F) : C


Minimun marks is 40

In the example above, A,B,C and D are the possible values that can be
assigned to the variable cGrade.
In each case of the constants, A to D, a statement or sequence of statements
would be executed.
E3062/5/10

Logical Structure Types And Basic Instruction

You would have noticed that every line has statement under it called “break”.
The break is the only thing that stops a case statement from continuing all the
way down through each case label under it. In fact, if you do not put break in,
the program will keep going down in the case statements, into other case
labels, until it reaches the end of a break.
However, the default part is the codes that would be executed if there were
no matching case of constant’s values.
E3062/5/11

Logical Structure Types And Basic Instruction

Activity 5A

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT…!

5.1 List 3 types of solution statement?


i._________________________
ii._________________________
iii._________________________

5.2 Define the basic form of the if statement and if-else statement?

5.3 What are the ‘break’ and ‘default’ statement are needed in the switch
statement ?
E3062/5/12

Logical Structure Types And Basic Instruction

Feedback To Activity 5A

5.1
i. if statement
ii. if else statement
iii switch statement

5.2
i. if (expression) statement;

ii if else (expression) statement_1, else statement_2;

5.3
 The ‘break’ statement is the only thing that stops a case statement
from continuing.
 The default statement is the part of the codes that would be
executed if there were no matching case of constant’s values.
E3062/5/13

Logical Structure Types And Basic Instruction

INPUT

5.1.3 Repetition (or Iteration) structure

The repetition (or iteration) structure permits a sequence of the instructions to


be executed repeatedly until certain condition is reached. The repetition
structure or loop in C++ comes in three forms while, do-while and for .

a) The while loop

The while loop repeats the body of the loop as long as the loop condition
holds. The basic form of the while statement is as below:

while (expression) statement;

In this loop, the expression is first evaluated. If it is true (not zero), the
statement (which can be a block is executed; if it is (zero), the statement is
bypassed
E3062/5/14

Logical Structure Types And Basic Instruction

is Yes
x >10?

No
Print x

x=x+1

Figure 5.5 : while loop


(Ref. C++ Through Examples-PSellapan)

Example 5.7

While ((cin>>amount) &&(amount > 0) && (amount<=balance))


{
balance = balance – amount;
cout<<”\n Please take your cash”<<amount;
}

b) The do-while loop


The do-while loop executes a statement as long as the loop condition
holds. The basic form of the do-while statement as below:

Do
statement
while (expression) ;
E3062/5/15

Logical Structure Types And Basic Instruction

This do-while loop is quite similar to the while loop except that the
expression is evaluated after the statement is executed. This means the
statement in the do-while will be executed at least once. In the while
statement, the statement will not be executed if the expression is false.

x=x+1

Print x

No is
x >10?

Yes

Figure 5.6 : do-while loop


(Ref. C++ Through Examples-PSellapan)

Example 5.8

//Program to illustrate a do-while loop


#include<iostream.h>
main()
{
int selection;
do
{
cout << “\n Menu ” << “\n” ;
cout << “\n 0. Exit ”;
cout << “\n 1. Append ”;
cout << “\n 2. Delete ”;
cout << “\n 3. Modify ”;
cout << “\n\n Enter selection : ”;
cin >> selection;
}
while (selection > 0 && selection < 4 );
return 0;
}
E3062/5/16

Logical Structure Types And Basic Instruction

In the example 5.8, the program displays the menu and then requests
a selection. If the selection is 1, 2, or 3, the menu is displayed again;
otherwise, the loop is terminated. Note that the loop is repeatedly executed so
long as the selection is 1,2 or 3.

c) The for Loop

The for loop repeats the body of the loop as long as the loop condition holds.
The basic form of the for loop as below:

for (initialization; condition test; incrementation)


{
statements;
}

 The initialization part typically refers to the initial value (if any) given
to a loop variable or counter. But it can also include the initialization
of any other variable. This initialization part is carried out just once at
the beginning of the loop.
 The expression part determines whether the loop execution should be
continued. If the expression is zero (false), the for loop is terminated,
if it is not zero (true), the for statement is executed.
 The incrementation part typically increments (or decrements) the loop
counter variable. This is done after the for statement is executed. This
part, like the initialization part, can also include the incrementation of
other variables.
E3062/5/17

Logical Structure Types And Basic Instruction

Example 5.9

#include<iostream.h>
main()
{
int iNum;

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


{
cout << iNum*iNum << “ ”;
}
}

The example 5.9, given is a very short program and it is easy for us to
understand the for loop.
First, an integer variable is declared. Then, in the initialization part, the
variable, iNum is set to 1. For the condition checking, iNum is checked to see
whether it is equal to or less than 10. In each cycle of the loop, iNum is
incremented by 1. Once iNum reaches 10, the loop exits. We can see that the
program calculates the square of the first ten natural numbers.

Program output:

1 4 9 16 25 36 49 64 81 100

5.2 Compiles And Run Program

To run a C++ program, we must first create it, then compile it, then link it with other
modules ( or other compiled programs), and finally run it. You can create a C++
program using the C++ editor. The editor is like a word processor that allows you to
type, edit and save your program. The program you create is called the source
module.
E3062/5/18

Logical Structure Types And Basic Instruction

After you have created the source program, you compiled it using the C++ compiler.
The compiler translates your C++ instructions into a machine-readable form. The
compiled program is called the object module.
Besides compiling the source module into an object module, the compiler also
generates information necessary for linker. The linker links the object module
generated by the compiler and any other object modules, your program may request
into a final executable module.

Tool Step Product

Editor Edit
Source module

Compiler Compile

Object module

Linker Link Library


Executable module

Run

Result/Output

Figure 5.7 : Steps in running a program


(Ref. C++ Through Examples-PSellapan)
E3062/5/19

Logical Structure Types And Basic Instruction

Feedback To Activity 5B

TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE


NEXT INPUT…!

5.1 What are three loops of iteration statements?


i._________________________
ii._________________________
iii._________________________

5.2 State the basic form of the for loop and write the part of program that uses a
for statement?

5.3 What is the compiler ?

5.4 What is the linker?


E3062/5/20

Logical Structure Types And Basic Instruction

Feedback To Activity 5B

5.1
i. while loop
ii. do-while loop
iii for loop

5.2
for loop form

for (initialization; expression; incrementation)


statement

Program that uses a for statement:

for (i=1; i<=20; i++)


Cout<< “\n Increment the first 20 numbers=”;

5.3
 The compiler translates your C++ instructions into a machine-
readable form.

5.4
 The linker links the object module generated by the compiler and
any other object modules.
E3062/5/21

Logical Structure Types And Basic Instruction

KEY FACTS

1. Logical structure or program control structures refer to the order of


execution of instructions in a program.

2. The three control structure generally we have to know are: sequence


structure , selection structure, repetition or iteration structure.

3. To run a C++ program, we must first create it, then compile it, then link it
with other modules and finally run it.
E3062/5/22

Logical Structure Types And Basic Instruction

4.
SELF-ASSESSMENT

You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 2
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.

Question 5-1

Write the program using selection and repetition structure (if, if else and for) to solve
following problem.

Enter 30 integer values in [1,200]. Find how many of these values fall in the range
1-50, 51-100, 101-150 and 151-200 ?

Question 5-2

Write the program using switch loop to solve following problem.

Given integer variables x ,y and a character variable ch. Input values for x,y and ch 9
the value for ch must be ‘a’, ‘m’, ‘s’, ‘d’ or ‘r’.
Compute and output

x + y if ch = ‘a’
x *y if ch = ‘m’
x - y if ch = ‘s’
x / y if ch = ‘d’
x % y if ch = ‘r’
E3062/5/23

Logical Structure Types And Basic Instruction

Feedback To Self-Assessment

** Please refer to your lecturer for checking purpose

** The feedback for this Self-assessment test is based on the student’s creativity as
long as the output meets the criteria required by the question.

The lecturer have to prepare a scheme or checklist as a guideline to check


students’ response.

Try Your Best!!!

You might also like