Professional Documents
Culture Documents
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
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
SR/PLT/301/0102/SC/2.0 5
Programming Logic and Techniques
Introduction
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.
Collecting the initial information (input) required for solving a particular problem.
SR/PLT/301/0102/SC/2.0 6
Programming Logic and Techniques
For that, we have to supply the three numbers to the computer as input.
SR/PLT/301/0102/SC/2.0 7
Programming Logic and Techniques
Steps in a Programming
Steps in a Programming
In the previous section, we have seen that solving a problem requires three steps:
Ø Input,
Ø Process
Ø Output.
.
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:
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.
Ø 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
.
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.
SR/PLT/301/0102/SC/2.0 10
Programming Logic and 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.
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.
SR/PLT/301/0102/SC/2.0 12
Programming Logic and Techniques
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.
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.
SR/PLT/301/0102/SC/2.0 13
Programming Logic and Techniques
Flowchart
Flowchart
It contains the sequence of data input operations, computations, decisions, results and
other relevant information pertaining to a particular problem.
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.
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.
SR/PLT/301/0102/SC/2.0 14
Programming Logic and Techniques
Symbols
Symbols Meaning
Start/Stop
Input/Output
Display
Process
Decision
Connector
Printout
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:
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
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
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
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.
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
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.
Ø Constants
Ø Variables
Constants: Constants can be defined as data elements that retain their values
throughout the execution of a program.
SR/PLT/301/0102/SC/2.0 21
Programming Logic and Techniques
Begin
Display “This is my first Pseudocode”;
End
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.
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:
SR/PLT/301/0102/SC/2.0 22
Programming Logic and Techniques
Variable Declaration
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 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.
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
integer number;
float quantity
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:
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:
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
Start
Declare number = 10
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.
In order to name a variable, we have to comply with certain rules. These rules are as
follows:
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
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:
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.
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.
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.
Start
Declare name
Accept name
Display name
Stop
SR/PLT/301/0102/SC/2.0 28
Programming Logic and Techniques
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.
Ø Arithmetic Operators
Ø Relational Operators
Ø Logical Operators
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.
Start
Declare num1,
num2, num3, result
Display “Enter
the first number”
Accept num1
Accept num2
Accept num3
Display result
Stop
SR/PLT/301/0102/SC/2.0 30
Programming Logic and Techniques
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.
Start
Display “Enter
the first number”
Accept num1
Accept num2
Display result
Stop
SR/PLT/301/0102/SC/2.0 31
Programming Logic and Techniques
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
Start
Display
“Enter item
Display “Enter
quantity”
Accept quantity
Display
“Enter rate”
Accept quantity
Display price
Stop
SR/PLT/301/0102/SC/2.0 32
Programming Logic and Techniques
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.
Every programming language provides the user with the following Relational
operators:
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.
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.
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.
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.
SR/PLT/301/0102/SC/2.0 34
Programming Logic and Techniques
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.
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.
SR/PLT/301/0102/SC/2.0 35
Programming Logic and Techniques
Sequence
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.
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
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
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..
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
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.
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.
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
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.
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.
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
SR/PLT/301/0102/SC/2.0 42
Programming Logic and Techniques
Iteration
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:
SR/PLT/301/0102/SC/2.0 43
Programming Logic and Techniques
Iteration (Contd.)
Iteration (Contd.)
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.
SR/PLT/301/0102/SC/2.0 44
Programming Logic and Techniques
Iteration (Contd.)
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:
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
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.
Begin
integer x, y, z
y = 1
Accept x
While (y <= 10)
{
z = x * y
Display z
y = y + 1
}
End
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.)
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.
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
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
Start
ctr = 0
total = 0
Is No
ctr < 5
Yes
Display “Enter a
number”
Accept num
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.
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.
SR/PLT/301/0102/SC/2.0 52
Programming Logic and Techniques
Start
ctr = 0
max = 0
Yes
Display
“Enter a number”
Yes
max = num
Display
max
Stop
SR/PLT/301/0102/SC/2.0 53
Programming Logic and Techniques
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:
The for loop contains three parts and the use is:
SR/PLT/301/0102/SC/2.0 54
Programming Logic and Techniques
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
d = x + y + (x + y) ------- step 5
y = y + 6 ------- step 6
d = d + y ------- step 7
SR/PLT/301/0102/SC/2.0 55
Programming Logic and Techniques
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
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.
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.
SR/PLT/301/0102/SC/2.0 56
Programming Logic and Techniques
Quiz
Quiz
Answer the following in brief:
SR/PLT/301/0102/SC/2.0 57
Programming Logic and Techniques
Solved Examples
Example 1
.
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.
.
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
.
Start
.
Declare three variables known as num, ctr and result
.
Initialize ctr and result to 1.
.
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.
.
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
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
.
Display the value of the variable max.
Example 7
Q) Write the Flowchart to generate the Fibbonacci series of the first 100 terms.
SR/PLT/301/0102/SC/2.0 60