You are on page 1of 60

STUDENT REFERENCE

Programming Logic And Techniques

globsyn technologies
XI - 11 & 12, Block - EP, Sector - V, Salt Lake Electronics Complex,
Calcutta - 700091, India

Globsyn
SR/PLT/301/0102/SC/2.0
All rights reserved. No part of this book shall be reproduced, stored in a retrieval
system, or transmitted by any means, electronic, mechanical, photocopying,
recording, or otherwise, without written permission from the publisher. No patent
liability is assumed with respect to the use of the information contained herein.

Globsyn
Programming Logic
and Techniques

Globsyn
Programming Logic and Techniques

Programming
Programming Logic Technique
and Techniques

•• Program
Program Development Life Cycle
Cycle
•• Algorithm
Algorithm Development
•• Problem
Arrays Solving
• Problem Solving

Module Objectives
Programming Logic and Techniques ------------------------------------------------------------------ 5
Introduction------------------------------------------------------------------------------------------------ 6
Steps in a Programming --------------------------------------------------------------------------------- 8
Structured Programming Techniques ---------------------------------------------------------------- 11
Good Programming Criteria -------------------------------------------------------------------------- 13
Flowchart ------------------------------------------------------------------------------------------------ 14
Symbols -------------------------------------------------------------------------------------------------- 15
First Flowchart ------------------------------------------------------------------------------------------ 16
Advantages of flowchart------------------------------------------------------------------------------- 17
Algorithm ------------------------------------------------------------------------------------------------ 18
Pseudocode ---------------------------------------------------------------------------------------------- 20
Introduction to Variables and Constants ------------------------------------------------------------ 21
Variable declaration ------------------------------------------------------------------------------------ 23
Instructions ---------------------------------------------------------------------------------------------- 27
Control Logic Structure-------------------------------------------------------------------------------- 35
Sequence ------------------------------------------------------------------------------------------------- 36
Selection ------------------------------------------------------------------------------------------------- 38
Iteration -------------------------------------------------------------------------------------------------- 43
The for loop --------------------------------------------------------------------------------------------- 54
Algorithm Checking Method ------------------------------------------------------------------------- 55
Quiz------------------------------------------------------------------------------------------------------- 57
Solved Examples------------------------------------------------------------------------------------------ 58

SR/PLT/301/0102/SC/2.0 4
Programming Logic and Techniques

Program Development Life Cycle

Objectives:
• Appreciate the requirement of a computer
program
• Get acquainted with the steps for programming
• Appreciate Structured Programming Techniques
• State the criteria of good programming
• Flowcharts
• Need of flowcharts

Programming Logic and Techniques

At the end of the chapter you will be able to:

Imbibe the importance of computer program


Get acquainted with the steps for Programming
Appreciate Structured Programming Techniques
State the Criteria for Good Programming
Draw a flowchart
Appreciate the necessity and advantages of a flowchart
Appreciate algorithms and pseudocodes
Appreciate variables and constants
Appreciate instructions
Appreciate the control logic structure
Appreciate iteration
Appreciate the various algorithm-checking methods

SR/PLT/301/0102/SC/2.0 5
Programming Logic and Techniques

Introduction

• A computer program can be defined as a series


of instructions issued to a computer to solve a
particular problem
• Such instructions are issued in a particular
programming language
• Advantages of programming:
– Concise logical expression of an event
– Prototyping of similar activities
– Automation

Introduction

Computer is the most exciting invention of the twentieth century. Now a days computers
are used in most operations, starting from a simple task like writing a letter to performing
complex task like Launching a Rocket.

In today’s life, we do not have the luxury to take an inordinately long time to perform a
particular piece of job. It is here that the computer has come as a boon for us. A job,
which earlier used to take several hours or even days to perform manually, can now be
performed within a few hours (or even seconds) with the help of a computer.

However, computers do have a serious limitation. Unlike Human beings, they lack the
power to think. The onus is then on us to brief this machine (computer) about the steps
for solving a particular problem.

For example, in order to add two numbers, we have to specify instructions to carry out the
operation. Such instructions are known as program.

In other words, we can say that a sequential set of instruction given to the computer to
solve a problem is called a program.

Problem solving in a computer is a step-by-step (systematic) process. There are basically


three steps by which computers find answer to queries (problem):

Collecting the initial information (input) required for solving a particular problem.

Working on that information. This is known as processing.

Obtaining the result to the problem. This result is called Output.

SR/PLT/301/0102/SC/2.0 6
Programming Logic and Techniques

The following example clarifies the above steps.

Lets find the average of three numbers

For that, we have to supply the three numbers to the computer as input.

Then, the computer operates on the numbers as per the instructions.


This constitutes the process.

Finally, the average (output) is displayed on the computer.

Define the term Program

SR/PLT/301/0102/SC/2.0 7
Programming Logic and Techniques

Steps in a Programming

• Understanding the program specification


– Problem Definition
– Requirement Analysis
• Designing a program model
• Coding the program
• Compilation of the program
• Errors
• Documenting the program

Steps in a Programming
In the previous section, we have seen that solving a problem requires three steps:

Ø Input,
Ø Process
Ø Output.

These series of steps are known as programming sequence.

The activities are as follows:

Ø Understanding program specification – This is the first step of programming


process. Here, we attempt to under the problem that is to be solved
Program specification in turn involves the following two steps:

.
Problem Definition: A problem definition, as the name suggests, is all about
ascertaining what the problem is.
Suppose we have to automate the payroll process of an organization. In such
a case, the problem definition is:

Automate the payroll process

However, mere defining a problem does not refer to its possible solution.

.
Requirement Analysis: This describes in details what a program is supposed
to do- determining its output and the precise inputs needed to solve the
problem.

SR/PLT/301/0102/SC/2.0 8
Programming Logic and Techniques

Thus, the Requirement Analysis for automating the payroll process would
involve the following steps:
• Ascertaining the existing manual payroll process.
• Finalizing the inputs required in accomplishing our purpose.
• Determining the output of the automated payroll process.

Ø Designing a program model – Once the program specification is clearly defined, we


try to obtain a solution to the problem.
The first step for this is preparing a logical model based on which the program is to be
developed. We represent the logic with the help of a series of instructions, which is
known as algorithm. An Algorithm is a set of instructions required for solving a specific
problem. Several tools like Flowcharts, Pseudocodes etc are used for this purpose.
These tools are described in detail in the subsequent chapter.

Ø Coding the program - This is the process of converting the algorithm (Flowcharts &
Pseudocodes) into an actual program. For this we choose a programming language
and use it to convert the logic into a full-fledged program.
When we speak in a particular language, (English, Hindi, etc.) we have to follow some
rules to ensure that our communication is effective. Computer languages are no
different. We issue instructions to a computer in the form of a programming language;
for that we have to follow certain rules. Such rules are known as syntaxes.

Ø Compilation of the Program - Once coding is complete, i.e. the program is written
and stored in the computer, the program is compiled or interpreted.
Now a question may arise in your mind what is compiled or interpreted.
The answer is that the machines (computer) can only communicate through a series
of zero (0) and one (1)- popularly known as machine code. Now the program that has
been written is required to be converted to machine code to make the computer
understand what has been written. For that a compiler or an interpreter is used
depending on the language. Each language has either a compiler or an interpreter.
The difference between a compiler and an interpreter is:

.
Compiled: In a compiler based language the program is written and then fed
to the Compiler. The compiler reads all the code and then converts to an
executable form that the computer understands.

.
Interpreted: In an interpreter based language the program is written and then
fed to the Interpreter. Interpreter reads a line, executes then goes forward, and
reads the next line.

Ø Error: Compilation may result in certain kinds of errors that are indicated by a
computer after the end of a compilation process.
We normally encounter three types of errors.

SR/PLT/301/0102/SC/2.0 9
Programming Logic and Techniques

These errors are:

.
Syntactical: This error occurs when an incorrect code is written in a program
i.e. the rules of a programming language is not followed.

.
Execution or Runtime: This error occurs at the time of executing a program
after compilation.

.
Logical: This error occurs due to defects in the logic of a program. Unlike
syntax and execution errors, the computer does not display logical errors.
They are reflected by the erroneous output generated by the program.

Ø Documenting the program – Once a program has been written and all the errors
have been successfully rectified, it is documented.

What is meant by Problem Definition?

SR/PLT/301/0102/SC/2.0 10
Programming Logic and Techniques

Structured Programming Techniques

• A structured program improves the


readability of the program and make it
more presentable.
• A structured program makes use of the
following tools:
– Subprograms or functions
– Comments
– Loops

Structured Programming Techniques

Earlier, programming was confined to the desired output only. A programmer was
satisfied if the program they developed could accomplish its tasks within a reasonable
time frame.

However, they were not concerned about the future- whether or not that program would
be equally effective after years. This attitude of the programmers soon resulted in
difficulties regarding the future modifications of the program. Every computer program
requires periodic modification to accommodate changing conditions and requirements.

Since the early programs were not properly pre-structured for periodic modification, it
proved tedious to modify them later. Therefore, many a times existing programs were
rewritten from the scratch. However, rewriting programs from the scratch resulted in
considerable wastage of time and effort.

In order to avoid such difficulties, programmers started paying more attention to the
manner in which the programs were written. The approach adopted for this purpose is
known as Structured Programming Technique.

Structured Programming Technique is a method of writing programs aiming for not


only the desired solution, but also ensuring that the program logic is clearly
understandable to others (future generations).

SR/PLT/301/0102/SC/2.0 11
Programming Logic and Techniques

This technique has certain features that facilitate clear understanding of the program
logic. One of its features is the concept of Subprograms. Very often, we come across a
program, which is quite long.

Naturally, as it is much easier for us to break down a huge task into smaller ones and
then develop codes for each of the smaller modules. These chunks are called
subprograms or functions.

Another important feature of Structured Programming is the use of comments.


Comments explain each step of a program. Thus, if a person other than the developer of
the program reads the program, it will be easier for him to understand it. The number of
comments to be inserted in a program depends upon the complexity of the program.

What is meant by Structured Programming?

SR/PLT/301/0102/SC/2.0 12
Programming Logic and Techniques

Good Programming Criteria

• Does it solve the problem stated?


• Does it work correctly under all situations?
• Does it have proper documentation?
• Does it have efficiency?

Good Programming Criteria

How does a programmer know that his program is correct? If he happens to be a novice,
he cannot rely on his past experiences and leave the decision to his intuition, which may
become costly for the software industry.

Hence in all cases if after solving a program we ask the following questions then the
probability of a deficit program is reduced to a great extent.

Does it solve the problem stated in the specification?

Does it work correctly under all conditions?

Does it have proper documentation?

Is it written using a modular approach?

Does it make efficient use of computer time and memory?

These criteria can be met automatically if sufficient thought and effort is invested in every
stage of program design.

As discussed, the first stage is understanding program specification. Now after the
program specification is clear to the developer he draws the flowchart for the program.

Why Documentation is required?

SR/PLT/301/0102/SC/2.0 13
Programming Logic and Techniques

Flowchart

• Flowchart is the symbolic representation of a program.


• Flowcharting Components are:
– Start/Stop
– Input/Output
– Decision
– Action/Predefined Process
– Connector Symbol

Flowchart

A flowchart is a symbolic representation of the step-by-step solution for a given problem.


It indicates the logical flow of the entire process adopted to solve a particular problem.

It contains the sequence of data input operations, computations, decisions, results and
other relevant information pertaining to a particular problem.

There are two types of flowcharts:

System Flowchart- This is normally used to describe the data flow and
operations for a data processing cycle (IPO).

They show the origin of data, the processing to be performed and the output to
be generated.

Program Flowchart- Programmers normally use Program flowcharts.

The logic for solving a particular problem is represented with the help of it.
This logic can easily be translated into a programming language.

Control instructions are best represented diagrammatically by using flow charts, which
provide a clear understanding of the algorithm used.

What is the difference between a System Flowchart and a Program


flowchart?

SR/PLT/301/0102/SC/2.0 14
Programming Logic and Techniques

Symbols

The symbols used in flow-chart are as follows:

Symbols Meaning
Start/Stop

Input/Output

Display

Process

Decision

Connector

Printout

What is the difference between Display and Output?

SR/PLT/301/0102/SC/2.0 15
Programming Logic and Techniques

First Flowchart
Let us now develop our first flowchart that displays a message.

Start

Display “This
is my first
flowchart”

Stop

SR/PLT/301/0102/SC/2.0 16
Programming Logic and Techniques

Advantages of Flowchart

• Easy understandability
• Pictorial representation
• Clear view of logical data flow
• Language independent

Advantages of flowchart
Easy understandability:

By viewing a flowchart, a person can easily understand the problem for which the
flowchart is drawn even if the person has not drawn the flowchart.

Pictorial representation:

As discussed it is a pictorial representation and some predefined symbols are


used for that. Now as the symbols are predefined, it makes clear what for the
flowchart is drawn in a single look.

Clear view of logical data flow:

Flowchart gives opportunity to see if the logic of the program is correct or not
before writing the program in any language. We can see the flow of data in the
flowchart, as it is a pictorial representation of a program.

Language independent:

Flowchart is not dependent on any language. It just follows some symbols and
simple English. After drawing the flowchart, it can be converted to any
programming language like C, C++, Java, etc.

SR/PLT/301/0102/SC/2.0 17
Programming Logic and Techniques

Algorithm

• Algorithm is a series of instructions that are


issued in a proper sequence to solve a problem
• Tools for developing Algorithms:
• Flowchart
• Pseudocode
• Should satisfy the following criteria:
– Must have a definite start and end
– Should have some input and output
– Should terminate after a certain number of steps
– Instructions should be unambiguous

Algorithm

An algorithm is a series of instructions issued in a proper sequence to solve a problem.


There are different ways to represent algorithms.

The two most important tools for representing algorithms are:

Ø Flowcharts: In a Flowchart, instructions are depicted using specific symbols.


Ø Pseudocodes: A Pseudocode is a series of instructions written in a simple English-
like language.
However, an algorithm is not prepared in any specific programming language i.e.
algorithm is language independent.

The idea of developing an algorithm is its easy understandability and implementation in


any programming language.

As discussed in the previous chapter algorithm is the first step towards developing a
program. It provides the programmers with a detailed blueprint with regards to the
solution of a problem. This blueprint is then converted into a full-fledged program written
in a particular programming language.

SR/PLT/301/0102/SC/2.0 18
Programming Logic and Techniques

An algorithm is to satisfy the following criteria:

There should be a definite starting and ending point for an algorithm.

There must be zero or more quantities (known as inputs) externally


supplied to the algorithm.

The algorithm should produce at least one output.

Each instruction must be unambiguous.

The algorithm should terminate after a definite number of steps.

The time and space an algorithm uses are two major measures of the
efficiency of an algorithm.

As we have already discussed about the flowchart in the previous chapter now lets
discuss about Pseudocode.

SR/PLT/301/0102/SC/2.0 19
Programming Logic and Techniques

Pseudocode

• A Pseudocode is text representation of a Flow Chart in


simple English, devoid of any programming language
syntax.

Pseudocode
A Pseudocode is the text representation of a Flow Chart in simple English. It is a good
practice for a beginner to first write a Pseudocode and then transforms the same to any
programming language.

One can also substitute the Pseudocode with a Flow Chart but the former is handy when
solving the logic for a large program. This is because in all the modern programming
languages instructions are issued in English-like statements. Therefore, the developers
are comfortable to convert a Pseudocode into a program.

A Pseudocode uses simple words like Accept (to accept data from the user), Display (to
print the data as output). Declaring a variable in Pseudocode does not require a data type
to be declared, but it helps the programmer in the long run.

Pseudocode is devoid of any programming language syntax

Now, let us prepare a Pseudocode for the flowchart that we have created in the previous
chapter:

Begin
Display “This is my first Flowchart”;
End

SR/PLT/301/0102/SC/2.0 20
Programming Logic and Techniques

Introduction to Variables and Constants

• A Variable is a memory location which can have


changeable values in a program.There are three
types of variables
• Alphanumeric
• Numeric
• String

• A Constant has a definite value in a program.A


Constant is of two types:
• Alphanumeric Constants
• Numeric Constants
• Every variable or constant has a name & data
type.

Introduction to Variables and Constants

By now, its clear that to develop an algorithm we require data. For example, to create an
algorithm that adds two numbers, we require the two numbers as data inputs.

The data elements used in an algorithm are of two types:

Ø Constants
Ø Variables
Constants: Constants can be defined as data elements that retain their values
throughout the execution of a program.

Constants can be divided into the following two types:

Alphanumeric Constants: Alphanumeric Constants normally consist of the following:

Ø Alphabets- A-Z, a-z


Ø Numbers- 0-9
Ø Special Symbols such as !, @, [] and so on.

A single Alphanumeric Constant can be defined as a character.

Examples of such characters are a, A, 9, # and so on.

There is a special type of alphanumeric constant known as String. A String can be


defined as a series of Alphanumeric Character Constants.

For example, “India” and “A009” are Stings.

SR/PLT/301/0102/SC/2.0 21
Programming Logic and Techniques

While representing Strings or Alphanumeric Characters in an algorithm, it is a good


practice to enclose the alphanumeric character constant within a single quote and an
alphanumeric String constant within double quotes.

Let us now prepare a Pseudocode to display an Alphanumeric String constant.

Begin
Display “This is my first Pseudocode”;
End

In the above Pseudocode, “This is my first Pseudocode” is an alphanumeric constant,


which does not change during the life cycle of the Pseudocode.

Numeric Constants: As the name suggests, these are used to store numeric values
such as Integers and decimals.

Alphanumeric constants have a major constraint. They cannot be used for calculations.

Numeric constants solve this problem. They can be used for calculations. Another feature
of numeric constants is that they can be either positive or negative.

There are two types Numeric constants:

Ø Integers: Integers are whole numbers like 10 and 20.


Ø Float: Floats are numbers that contain decimals. An example of a float value is 10.25.

Variables: Variables are data elements whose values change during the execution of an
algorithm. We know that data is stored in the memory of a computer. Therefore, to
access the data stored in a particular memory location, we have to earmark that location
in some way.

Variables are used to assign a logical name to a memory location to identify such
location.

Suppose, we have to multiply two and four and display the result. Once the numbers are
multiplied and the product is displayed, the result is lost forever from the memory of the
computer.

Now, if there is a need to use this product in any further calculations, we have to again
perform the multiplication. This will result in a duplication of efforts, which is not a healthy
practice. However, if a variable is used for storing the result, we can easily retrieve it from
the memory for any further use.

Like constants, variables can also be classified into the following two groups:

Ø Alphanumeric: We use Alphanumeric variables to store Alphanumeric data.


Ø Numeric: Numeric variables, as the name suggests, are capable of storing numeric
data. Numeric variables can either be Integer variable and a Float variable..

SR/PLT/301/0102/SC/2.0 22
Programming Logic and Techniques

Variable Declaration

• Variables should be declared before they are used in a


program
• Variable is declared in the following manner
data type varaiable_name
• A String variable should be declared in the following
manner:
data type varaiable_name [size]
• Values can be assigned to the variables either at the
time of its declaration or any time after that.

Variable declaration
We have to declare variables before we can use them in a program.

Variables are declared to communicate to the computers the type of the variables that are
going to be used in a particular program. This is required because the amount of memory
space required for storing an alphanumeric variable is different for that required to store a
Numeric variable.

When a variable stores an Alphanumeric value, it cannot be used for performing any
calculations. Thus, if we declare a variable as alphanumeric, the computer knows that the
value stored in the variable will not be used for performing any calculations.

In a Pseudocode, a variable is declared in the following manner:

data type variable_name;

In the above declaration, data type represents the type of the data that can be stored in
the variable and variable_name is the name of the variable.

The following code snippet illustrates the declaration of an Alphanumeric variable:

character ch;

In the above example, the variable ch can accept only one value. In order to store String
variables, the declaration is:

character address[10];

In the above example, the String variable address can store upto 10 characters.

SR/PLT/301/0102/SC/2.0 23
Programming Logic and Techniques

The following command declares an Integer variable:

integer number;

The following code snippet shows us how to declare a Float variable:

float quantity

Assignment of values to a variable

Now, that we know how to declare variables, the next step is to learn about the
assignment of values to variables. In a program, we can assign values to variables in the
following two places:

When we declare a variable

At any place after the declaration of the variable

For example, we want to declare an alphanumeric variable called name and assign to it
the value ‘Smith’. The following code snippet shows us how to declare and assign values
to the name variable at the time of declaration:

character name[10] = “Smith”

However, if we want to assign a value to a variable after its declaration, then it has to be
done in the following manner:

character name[10]

name = “Smith”

Let us now see a complete program wherein we shall display the values assigned to an
alphanumeric, numeric and a float variable.

Begin
character name
integer number = 10
float quantity = 10.22
name = “Ram”
Display name
Display number
Display quantity
End

SR/PLT/301/0102/SC/2.0 24
Programming Logic and Techniques

Let us now prepare a Flowchart depicting the above Pseudocode.

Start

Declare name = “Smith”

Declare number = 10

Declare quantity = 10.22

Display name

Display number

Display quantity

Stop

The = symbol in the program is called assignment operator and is used for assignment of
values to variables.

Rules For naming Variables

In order to name a variable, we have to comply with certain rules. These rules are as
follows:

Ø As a developer, we can give any name to a variable. However, we must remember


that the name given to a variable should be meaningful and should briefly describe
what the variable stands for in the program. For example, a variable that is used to
store names should be nomenclated as Name, so that anybody reading our program
can easily understand what this variable stands for in the program. If we name a
variable that is used to store the name of a student as address, it is not easy for
anyone reading our program to understand what this variable does
Ø We cannot give an identical name to two variables. For example, if we store the
names of two students in two variables, then we have to give two different names to
these variables even if they store the same type of data.

SR/PLT/301/0102/SC/2.0 25
Programming Logic and Techniques

Ø It is a good practice to ensure that the first letter of a variable is an alphabet and the
subsequent letter can be alphabets or digits. For example, we cannot name a variable
as 9ABC. However, we can definitely name the variable as A9BC or ABC9.
Ø Every programming language has some words that are used to instruct the computers
to perform specific functions. For example, in C++, the cin command is used to
accept inputs. Such words are known as keywords. Therefore in C++, we cannot
name a variable as cin. Therefore, we can safely assume that keywords cannot be
used as variable names.
Ø The variable naming rules given above are general and more or less apply to every
programming language. However, there are various other programming naming
conventions which vary from program to program.

SR/PLT/301/0102/SC/2.0 26
Programming Logic and Techniques

Instructions

• Executable lines in a program are called instructions.


• Instructions are combination of commands, variables
and constants.
• There are four types of instructions. They are:
– Type declaration Instructions
– Input/Output Instructions
– Operators:Are of the following three types
– Arithmetic
– Relational
– Logical
– Control Instructions

Instructions
Instructions are executable lines in a program. A single line is called a statement. It can
contain command, variables and constants. For example, at the time of declaration of a
variable, we use the following statement:

character address = “Calcutta”

In practice, when we use the above statement, we actually instruct the computer to name
a particular memory location as address and store the value Calcutta in that variable.
Therefore, we can call the above statement as an Instruction.

Different types of constants, variables and commands are combined to form an


instruction.
For example, in order to display the address variable, we give the following instruction:
Display address

Thus, in the above statement, we find that the instruction to display the value of the
address variable actually involves the combination of a command, Display and a variable
address.

Instructions are written using a particular language. So, we have to follow their syntax.

Four types of instructions are generally used.

They are:
1. Type Declaration Instructions: We are already familiar with this. They are used for
declaring variables and specifying their datatypes.

SR/PLT/301/0102/SC/2.0 27
Programming Logic and Techniques

2. Input/Output instructions: These instructions are used to perform input and output
operations. For example, to multiply two numbers, we have to supply the numbers as
data inputs.

When the product of the two numbers are displayed to the user, it is known as data
output.

We have already seen in earlier examples that for displaying any information to the
user, we use the Display command. Thus, Display is an Output instruction.

In order to accept any data from the user, we use the Accept command. Let us now
study an algorithm that accepts the name of the user and thereafter displays the
user’s name.

The flowchart for the above problem is as follows:

Start

Declare name

Display “Enter name”

Accept name

Display “ name is:"

Display name

Stop

SR/PLT/301/0102/SC/2.0 28
Programming Logic and Techniques

The Pseudocode of the above flowchart is as follows:

Begin
character name[10]
Display “Enter Your Name”
Accept name
Display “Your name is:”
Display name
End

In the above program, the user is prompted to enter the name. The Accept command
is used to accept the input from the user, which in this case is the name of the user.
The input from the user is stored in a String variable called name and that is
displayed using the Display command.

3. Operators: The algorithm that we have prepared above merely accepted inputs from
the users and then displayed them. However, computer programs can do much more
than that.

A computer can perform simple and complex computations, compare the relationship
between a variable and a constant or between two variables and many other tasks.

To perform such tasks with ease, every programming language provides the user with
certain tools. Such tools are known as Operators.

Operators are divided into the following three categories:

Ø Arithmetic Operators
Ø Relational Operators
Ø Logical Operators

Arithmetic Operators: Arithmetic operators enable the user to perform various


arithmetical calculations.

Operations Symbols

Addition +

Subtraction -

Multiplication *

Division /

Modulous %

The above symbols are called arithmetic operators. Modulo operator returns the
remainder when we divide one integer with another.

SR/PLT/301/0102/SC/2.0 29
Programming Logic and Techniques

Examples:

1. In the algorithm below, we shall try to find out the average of three numbers after
accepting the numbers from the users.

The flowchart to solve the problem is:

Start

Declare num1,
num2, num3, result

Display “Enter
the first number”

Accept num1

Display “Enter the


second number”

Accept num2

Display “Enter the


third number”

Accept num3

result = (num1 + num2 + num3)/3

Display result

Stop

SR/PLT/301/0102/SC/2.0 30
Programming Logic and Techniques

The Pseudocode for the above problem is as follows:

Begin
integer num1, num2, num3, avg
Display “Enter the first number”
Accept num1
Display “Enter the second number”
Accept num2
Display “Enter the third number”
Accept num3
avg = (num1+ num2 + num3)/3
Display avg
End

2. In the example below, we shall find the remainder of two numbers after accepting
them from the user.

The flowchart and Pseudocode for this problem is as follows:

Start

Declare num1, num2, result

Display “Enter
the first number”

Accept num1

Display “Enter the


second number”

Accept num2

result = num1 % num2

Display result

Stop

SR/PLT/301/0102/SC/2.0 31
Programming Logic and Techniques

Following is the Pseudocode for the above problem:

Begin
integer num1, num2, result
Display “ Enter the first number”
Accept num1
Display “Enter the second number”
Accept num2
result = num1 % num2
Display num2
End

3. Let us consider another example of an arithmetic operator. The Flowchart given


below accepts the item name, rate and quantity from the user and displays the
price (rate * quantity).

Start

Declare item name, quantity, rate, price

Display
“Enter item

Accept item name

Display “Enter
quantity”

Accept quantity

Display
“Enter rate”

Accept quantity

price = quantity * rate

Display price
Stop

SR/PLT/301/0102/SC/2.0 32
Programming Logic and Techniques

Following is the Pseudocode for the above problem:

Begin
character item_name[10]
integer quantity, rate, price
Display “Enter the name of the item”
Accept item_name
Display “Enter item quantity”
Accept quantity
Display “Enter rate”
Accept rate
price = quantity * rate
Display price
End

Relational Operators

A Relational operator enables us to compare the values of two variables or the value
of one variable with a constant.

For example, we can use Relational operators to ascertain whether a particular


variable is equal to, greater than another variable, or constant.

Every programming language provides the user with the following Relational
operators:

Some of the Relational operators are given below in the table:

Operator Meaning
> Greater than
< Less than
== Equal to
!= Not Equal to
>= Greater than or equal to
<= Less than or equal to

The (==) operator is used to test whether a particular variable is equal to another variable
or constant. The (!=) operator is just opposite in functionality to the == operator.

We shall consider examples of relational operators in the subsequent section.

SR/PLT/301/0102/SC/2.0 33
Programming Logic and Techniques

Logical Operators

The three Logical operators that are supported by any programming language are:

Ø And
Ø Or
Ø Not

The main purpose of using logical operators is to combine two relational operators.
Let us consider that we have to check whether a particular variable, say num is equal
to 10 and another variable say num1 greater than 20.

In order to represent the above checking in a program, we have to implement it in the


following manner:

(number == 10 and number1 > 20)

Normally, Logical operators return a True or False indicating whether the checking
has been successful or not. If the checking is successful, then a True is returned.
Otherwise, the returned value is False.

The And operator returns a True when both the conditions are satisfied. Thus in the
above example, the condition evaluates to True if the value of the number variable is
equal to 10 and the value of the number1 variable is more than 20.

The OR operator returns true if any one of the specified conditions are satisfied.

Let us consider the following code snippet:

(number == 10 or number1 > 20)

In the above statement, the expression returns TRUE if either the value of the
variable number is equal to 10 or the value of the variable number1 is more than 20.

The NOT is used to convert the result returned by a condition. If a condition returns
TRUE, then the NOT converts it to false and vice-versa.

4. Control Instructions: The control instructions determine the flow of control in a


program. They determine the order in which the various instructions in a program are
to be executed.

We shall learn more about Control Instructions in the subsequent sections.

SR/PLT/301/0102/SC/2.0 34
Programming Logic and Techniques

Control Logic Structure

• There are three types of Control Logic Structure


namely:
– Sequence
– Selection
– Iteration

Control Logic Structure

In 1968, Dijkstra’s a computer guru, opened a new horizon in the field of computer
programming.

Earlier, when there was a need to skip certain instructions and go to a particular set of
instructions, programmers used ‘GOTO’ to achieve this particular task. GOTO had its
origin in the Assembly equivalent ‘JUMP’ and programmers thought it to be indispensable
in writing large programs.

However, Dijkstra’s article clearly stated the disadvantages of GOTO giving a new
alternative definition of Structured Programming Language. According to him, only three
techniques are to be used namely Sequence, Selection and Iteration to successfully write
programs of any size.

Gradually in 1975, Jackson’s Structured Program came up followed by the Warnier-Orr


methodology, which were subsequently replaced by other techniques.

The flow of a flowchart depends upon the problem, which you are solving. The control
logic structure of the flowchart may be Sequential or Selection or Iteration.

Now lets discuss broadly the three control logic structures.

SR/PLT/301/0102/SC/2.0 35
Programming Logic and Techniques

Sequence

• Sequence is a programming technique in which a series


of instructions take place one after the other.
• All the instructions will have to be executed in order to
achieve the desired result.
• If a particular step is omitted then the required output
cannot be achieved

Sequence
Sequence is a programming technique where a particular program contains a series of
instructions and each instruction is executed one after the other. All the instructions are to
be executed at least once for the complete execution of the program. If any step is
missed, we shall not be able to achieve our desired result.

We have already seen examples of sequential programming in the algorithms and


created in the preceding sections. However, in order to refresh our memory let us create
another algorithm involving sequential instructions.

In the example below, let’s create a Flowchart that adds two numbers and displays the
result.

SR/PLT/301/0102/SC/2.0 36
Programming Logic and Techniques

Pseudocode for the above flowchart is as follows:

Begin
integer x, y, z
Accept x, y
z = x + y
Display z
End

Thus in the above algorithm, in order to display the sum of two numbers, we have to
execute each of the above steps in a sequential manner i.e., one after the other. If any of
the steps are missed, we shall not be able to achieve our goal.

SR/PLT/301/0102/SC/2.0 37
Programming Logic and Techniques

Selection

• Selection means determining which of the two


or more paths to follow under a given condition.
• Implemented with the help of If-Else-Endif construct in a
Pseudocode
• In a flowchart decision making is represented by
the symbol given below:

Selection

In the case of selection, unlike a sequence, the statements jump from one point to the
other depending on a specific criterion. Selection is used when we have to take different
courses of actions depending upon certain criteria. If a particular criterion is met, we
execute a particular set of instructions. Otherwise, we execute another set of
instructions..

In a program, this decision-making is performed with the help of an if –else construct.


The relational and logical operators that we have learnt earlier are used with the if –
else construct to ascertain whether a specific condition is being satisfied.

The If statement is used when there is more than one course of action to be taken based
on certain conditions. Each If statement ends with an Endif statement in most of the
languages.

Many a times when we take a decision, we also think of the possible alternative course of
actions. The Else statement provides another course of action when the given condition
is not satisfied. The statements after the Else statement are executed only if the condition
written with If is not satisfied.

In other words, if the condition evaluated by the If clause is satisfied, the instructions
following the If clause are executed. If the condition evaluated by the If clause is not
satisfied, then the statements following the Else clause are executed.

Example:

1. Let us take an example where we have to use the If –Else construct. Suppose, we
have to develop a program where we allow an individual to vote and if his age is 18 or
above. Otherwise, a message is to be displayed informing him that he cannot vote.

SR/PLT/301/0102/SC/2.0 38
Programming Logic and Techniques

The following Pseudocode will represent this logic:

Begin
integer age
Accept age
If (age>=18)
{
Display “Can vote”
}
Else
{
Display “Cannot vote”
}
Endif
End

In the above Pseudocode, we have used a relational operator (>=) to test whether the
age of the individual is equal to or greater than 18. If he satisfies the requisite condition,
a message is displayed informing him Can vote. The else clause is used in those cases
where the age is less than 18 then the message is displayed Cannot vote.

In a pseudocode, it is always a good practice to enclose the series of instructions


following the if and else within braces (parenthesis).

The flowchart for this problem is given in the next page. In this flowchart, we have used
the decision box to test the if condition.

Start

Declare age

Accept age

If age Yes
Display
>= 18
“Can vote”

No
Display
“Cannot vote”

Stop

SR/PLT/301/0102/SC/2.0 39
Programming Logic and Techniques

2. Let us take another example where we shall determine whether a particular number is
even or odd.

The Flowchart for above problem is given in the next page.

Start

Declare num,
result

Accept num

result = num%2

If Yes
result Display “Even
number”
== 0

No

Display “Odd
number”

Stop

We all know that a particular number is even if it is divisible by two. Hence, when an even
number is divided by two the remainder is zero. This remainder is stored in the variable
result.

In the decision box, we check whether the result is equivalent to zero or not. If it is zero,
we display a message “Even Number”. If the result is not equivalent to zero, it implies that
the number is an odd number. Thus, we shall display a message “Odd Number”.

SR/PLT/301/0102/SC/2.0 40
Programming Logic and Techniques

The Pseudocode, for the problem is as follows:

Begin
integer num, result
result = num % 2
If (result ==0)
{
Display “Even Number”
}
Else
{
Display “Odd Number”
}
Endif
End

We can come across situations where we have to use an If clause within an Else clause
or within another If clause.

3. Let us consider an example to find the largest number among three different positive
numbers.

The flowchart for the above example is in the next page:

SR/PLT/301/0102/SC/2.0 41
Programming Logic and Techniques

In the above flowchart, we have accepted three numbers from the users and stored them
in variables x, y and z respectively. After which we compare variable x with variable y.

If x is larger than y, then we compare variable x with variable z. If x is larger than z, then x
is largest number. But, if variable x is less than variable y, then we compare variable y
with variable z. If, y is larger than z, then y is the largest among the three numbers.
Otherwise, z is the largest.

The Pseudocode, of the above example is as follows:

Begin
input x,y,z
Accept x
Accept y
Accept z
If (x>y)
{
If (x>z)
{
Display “x is the largest”
}
Else
{
Display “z is the largest”
}
Endif
If (y>z)
{
Display “y is the largest”
}
Else
{
Display “z is the largest”
}
Endif }
Endif
End

Find out an alternative way to pick up the highest of three


numbers

SR/PLT/301/0102/SC/2.0 42
Programming Logic and Techniques

Iteration

• This logic structure is used when we need to repeat


some steps within a program.
• An entire cycle of repetition is called a loop. The 2 most
common varieties are:
– While
– Do..while
– For loop

Iteration

This logic structure is used when we need to repeat some steps within a program. In a
program, there can be situations where we have to execute a series of instructions
repeatedly.

In computer terminology, these sets of instructions are kept within a loop. The loop
concept helps in cutting down the code size.

Say, we have to write a program to display hundred numbers. Without the concept of
looping, we have to develop the code (for accepting and displaying the numbers) 100
times- a massive task.

With the help of loops, we can place the instructions to be repeated in one particular
place.

Almost all programming languages support the following two kinds of loops:

While Loop – This will be executed as long as certain condition is true.


Minimum execution is zero

Do…While Loop – This is executed at least once and for subsequent


times if the condition remains true.

For loop - This loop also executed a set of statements depending on


certain condition. It has three parts.

SR/PLT/301/0102/SC/2.0 43
Programming Logic and Techniques

Iteration (Contd.)

A loop has 3 critical points


• Loop counter initialization
• Loop condition
• Loop counter increment/decrement

Iteration (Contd.)

We have to follow certain rules for developing Loop constructs.

The following three critical points are to be remembered in this regard.


1. Loop Counter Initialization – Before we start writing a loop, a counter must
be declared and initialized. A counter is a variable that is
incremented/decremented each time the instructions within a loop is
executed (elucidated later).
2. Loop Condition – The condition based on which the iterations will occur
3. Loop Counter Increment/Decrement – Change the loop counter
appropriately before going for the next iteration as this may later lead to
infinite or non-terminating loops.

The repetitive tasks written within the loop constructs (Do…. Enddo) make up the body of
the loop. However, we must ensure that a loop has a terminating condition.

In Do..While Loop, the statements within the loop must be executed


at least once, but in While loop, it may be even None; because in
Do… While Loop, the condition is checked at the end whilst in While
loop, the condition is checked in the beginning.

SR/PLT/301/0102/SC/2.0 44
Programming Logic and Techniques

Iteration (Contd.)

• In a while loop the loop condition is evaluated to


TRUE before the loop body gets executed.

Iteration (Contd.)
Here we shall learn about the While loop.

In case of a While loop the condition is first evaluated. If this condition is satisfied, then
only the instructions specified in the body of the loop are executed. In a While loop, the
condition is evaluated after each iteration. The body of the While loop is executed as long
as this condition is satisfied.

However, if the loop condition is not satisfied, the body of the loop will not be executed at
all.

Example:

1. Let’s display a series of numbers from 1 to 100.

The pseudocode for this problem is as follows:

Begin
integer x = 1
While (x <=100)
{
Display x
x = x + 1
}
End

SR/PLT/301/0102/SC/2.0 45
Programming Logic and Techniques

The flowchart for the problem is as follows:

Start

Declare x = 1

Is No
x <=100

Yes
Display x

x=x+1 Stop

2. Let us consider another example where we shall accept a number from the user and
generate a multiplication table of up to 10 for that number.

The pseudocode for the above problem is as follows:

Begin
integer x, y, z
y = 1
Accept x
While (y <= 10)
{
z = x * y
Display z
y = y + 1
}
End

The flowchart for the problem is as follows:

SR/PLT/301/0102/SC/2.0 46
Programming Logic and Techniques

Start

Declare x, y, z

y=1

Accept x

No
Is
y <= 10

Yes

z= x * y

Display z

y=y+1
Stop

SR/PLT/301/0102/SC/2.0 47
Programming Logic and Techniques

Iteration (Contd.)

• In a do.. while loop the loop condition is


evaluated to TRUE after the loop body gets executed
at least once

Iteration (Contd.)

The body of the While loop may not be executed at all if the loop condition is not
satisfied.

However, we may have to face a situation where the loop body is to be executed at least
once, irrespective of the fact whether or not the loop condition is satisfied. In order to help
us in such circumstances, most programming languages support a special kind of loop
known as a Do..While loop.

In a Do..While loop, the loop condition is evaluated after the loop body is executed at
least once.

Example:

1. Let us again consider the example where we shall print a series of numbers from 1 to
100. But, this time we shall solve this problem with the help of a Do..While loop. The
flowchart for this is as follows:

SR/PLT/301/0102/SC/2.0 48
Programming Logic and Techniques

Start

Declare x = 1

Display x

Is No
x <=100

Yes
x=x+1 Stop

From the above flowchart, we can see that the variable x is displayed once before the
While loop condition is evaluated. Thus, even if by mistake, we initialize the variable x to
101, its value is displayed before we check the loop condition.

But, in case of a While loop, if the variable x is initialized to a value which is higher than
100, x is not be displayed at all.

Now, let us convert the above flowchart into a Pseudocode.

Begin
integer x
x = 1
Do
{
Display x;
x = x + 1;
} While (x<=100)
End

2. Let’s solve another problem where we shall combine the concepts of Iteration and
Selection. We accept five numbers from the user and see how many of these numbers
are divisible by 10.

SR/PLT/301/0102/SC/2.0 49
Programming Logic and Techniques

The Pseudocode is:

Begin
integer num, result, ctr, total
ctr = 0
total= 0
While (ctr < 5)
{
Display “ Enter a number”
Accept num
result = num % 10
If (result == 0)
{
total = total + 1
}
Endif
ctr = ctr + 1
}
Display total
End

SR/PLT/301/0102/SC/2.0 50
Programming Logic and Techniques

The flowchart for the above program is :

Start

Declare num, result,


ctr, total

ctr = 0
total = 0

Is No
ctr < 5

Yes

Display “Enter a
number”

Accept num

result = num %10

ctr = ctr + 1

No Is
result == 0

Yes
total = total + 1

Display
total Stop

SR/PLT/301/0102/SC/2.0 51
Programming Logic and Techniques

Let us now find out the highest value among hundred positive numbers entered by the
user.

The Pseudocode for this is:

Begin
integer num, ctr, max
ctr = 0
max = 0
While ( ctr <=100)
{
Display “ Enter a number”
Accept num
If (num > max)
{
max = num
}
Endif
ctr = ctr +1
}
Display max
End

In the above Pseudocode, we are initializing a variable called max with 0. The number
that is entered is compared with max.

If the number entered is greater than max, we assign this number to max. This process is
continued until the value of ctr is equal to 100.

The flowchart for the above problem is as follows:

SR/PLT/301/0102/SC/2.0 52
Programming Logic and Techniques

Start

Declare num, ctr,


max

ctr = 0
max = 0

Is ctr <= 100 No

Yes

Display
“Enter a number”

ctr = ctr + 1 Accept num

No If num > max

Yes

max = num

Display
max

Stop

SR/PLT/301/0102/SC/2.0 53
Programming Logic and Techniques

The for loop


The for loop executes a set of statements for certain
number of times until the condition is matched
Syntax:
For (initialization;condition; expression)
{
statements;
}
initialization: to initialize a variable
condition: to test a condition, it returns boolean value
expression: is used for increment or decrement the
value of variable

The for loop

The for loop executes a set of statements for certain number of times until the condition is
matched.
The general syntax for the for loop:

for (initialization ; condition ; expression)


{
statements;
}

The for loop contains three parts and the use is:

initialization: to initialize a variable

condition: to test a condition, it returns boolean value

expression: is used for increment or decrement the value of variable

SR/PLT/301/0102/SC/2.0 54
Programming Logic and Techniques

Algorithm Checking Method

• Checks the correctness and validity of an


algorithm. The following are the three types of
Algorithm Checking Method:
– Dry Run
– Independent Inspection
– Structured Walk-through

Algorithm Checking Method

In order to check whether the Algorithm we have developed gives the desired
output or not, we make use of certain tools.
Following are three such tools:
1. Dry Run - Dry Run is a manual way of testing an algorithm for its accuracy. In
this method, a table is prepared with columns for each variable used in the
algorithm. The value of each variable is updated in the table as we proceed through
the algorithm, one step at a time.
For e.g.
Begin ------- step 1

int x = 5 ------- step 2

int y = 10 ------- step 3

int d = 0 ------- step 4

d = x + y + (x + y) ------- step 5

y = y + 6 ------- step 6

d = d + y ------- step 7

DISPLAY x, y, d ------- step 8

END ------------ step 9

SR/PLT/301/0102/SC/2.0 55
Programming Logic and Techniques

Dry Run Table

x y d

Initial Value 5 10 0

After step 5 5 10 30

After step 6 5 16 30

After step 7 5 16 40

So the result displayed on the screen is 5, 16, 40.

2. Independent Inspection - Independent inspection is another method of checking the


correctness of an algorithm. In this method, the specification and designed solution are
handled. Inspection or dry run checks the solution.

This method must be adopted as it brings objectivity in the design of the algorithm. The
person who has developed the algorithm shall always view it with a bias and may not
foresee situations that may arise, other than those already taken care of. While a person
who has not developed the algorithm might prove to be wiser in this respect.

3. Structured Walk-through - Yet another method of checking the correctness of an


algorithm is by Structured Walk-through method.

This method involves a presentation of the algorithm to a team of peers. The team points
out inconsistencies, better procedures and errors if any in the algorithm. Spotting errors
becomes easier while explaining the logic to others.

The solution is either accepted completely, or accepted after minor modifications, or


rejected completely. It is more productive than a dry run or an independent inspection.

SR/PLT/301/0102/SC/2.0 56
Programming Logic and Techniques

Quiz

Quiz
Answer the following in brief:

1. Define an Algorithm, a Flow Chart and a Pseudocode


2. What is a Variable?
3. How does it differ from a Constant?
4. What is a data type? Name the fundamental ones.
5. Prepare a flowchart and a Pseudocode to accept a number from the user and to
find its factorial.
6. Write a Pseudocode to accept two numbers from the user and interchange their
values.
7. Prepare a flowchart to accept distance and time from the user and calculate
speed.
8. Write a Pseudocode to generate the following series:
9. 1,2,3,5…
10. Prepare a Flowchart that will accept 50 numbers from the user and find the
minimum one from among these numbers.

SR/PLT/301/0102/SC/2.0 57
Programming Logic and Techniques

Solved Examples
Example 1

Q) Write an algorithm to exchange the values of two variables A and B.

Ø The algorithm is as follows:

.
Start

.
Declare the variables A and B.

.
Assign the variables the given values.

.
Declare a temporary variable called t.

.
Save the original value of A in t.

.
Assign to A the original value of B.

.
Assign to B the original value of A, which is stored in t.

.
End

Example 2

Q) Given a set of examination marks of n students (in the range of 0 to 100). Make a
count of the number of students that passed the examination. A pass is awarded for all
marks of 50 and above.

Ø The algorithm is as follows:

.
Start

.
Prompt the user for the number of students whose marks have to be
processed.

.
Declare a variable “count” and initialize it to 0.

.
While the Value of “count” is equal to or less than the user input, read the
marks of the corresponding student. If it is a pass (i.e. greater than or equal to
50) then add one to count.

.
Write out the total number of passes.

.
End

SR/PLT/301/0102/SC/2.0 58
Programming Logic and Techniques

Example 3

Q) Calculate factorial of any positive integer

Ø The algorithm is as follows:

.
Start

.
Declare three variables known as num, ctr and result

.
Initialize ctr and result to 1.

.Accept the number for which factorial is to be determined and store it in


the variable num

.
While the value of the variable ctr is less than the value of the variable num,
perform the following:

.
Multiply ctr with result and store the value in the variable result.

.
Increment ctr by 1.

.
Display the value of the variable result

Example 4

Q) Design an algorithm that accepts an integer and then display a message to indicate
whether it is a positive or negetive number.

Ø The algorithm description is as follows:

.
Start

.
Accept the number from the user.

.
If the number is more than zero, then it is positive. If the number is less than
zero, it is negetive.

.
Display appropriate message in each case

.
End

Example 5

Q) Print the highest marks obtained in an examination for 30 students.

Ø To solve this problem, the following steps to be followed:

SR/PLT/301/0102/SC/2.0 59
Programming Logic and Techniques

.
Start

.
Declare three integer variables known as ctr, max and marks

.
Initialize the variable ctr to 0

.
Initialize the value of variable max to 0

.
While the value of ctr is less than or equal to 29, perform the following

• Accept the marks scored by the students in the variable marks.


• Check if the value of marks is greater than max. If so, assign the value
stored in marks to the variable max.
• Increment ctr by 1.

.
Display the value of the variable max.

Example 7

Q) Write the Flowchart to generate the Fibbonacci series of the first 100 terms.

Declare integer t1,t2,sum,n


n=0
t1=1
t2=1
Display t1,t2
While(n<98)
Do
Sum=t1+t2
Display sum
t1=t2
t2=sum
Increase n by 1
Enddo

SR/PLT/301/0102/SC/2.0 60

You might also like