View
244
Download
0
Category
Preview:
Citation preview
8/8/2019 PLT YSM Pro
1/60
Globsyn
STUDENT REFERENCE
Programming Logic And Techniques
globsyn technologiesXI - 11 & 12, Block - EP, Sector - V, Salt Lake Electronics Complex,
Calcutta - 700091, India
8/8/2019 PLT YSM Pro
2/60
Globsyn
All rights reserved. No part of this book shall be reproduced, stored in a retrievalsystem, or transmitted by any means, electronic, mechanical, photocopying,recording, or otherwise, without written permission from the publisher. No patentliability is assumed with respect to the use of the information contained herein.
SR/PLT/301/0102/SC/2.0
8/8/2019 PLT YSM Pro
3/60
Globsyn
Programming Logic
and Techniques
8/8/2019 PLT YSM Pro
4/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 4
Module Objectives
Programming Logic and Techniques ------------------------------------------------------------------5Introduction------------------------------------------------------------------------------------------------ 6Steps in a Programming --------------------------------------------------------------------------------- 8
Structured Programming Techniques---------------------------------------------------------------- 11
Good Programming Criteria -------------------------------------------------------------------------- 13Flowchart ------------------------------------------------------------------------------------------------ 14
Symbols -------------------------------------------------------------------------------------------------- 15
First Flowchart ------------------------------------------------------------------------------------------ 16
Advantages of flowchart------------------------------------------------------------------------------- 17Algorithm------------------------------------------------------------------------------------------------ 18
Pseudocode ---------------------------------------------------------------------------------------------- 20
Introduction to Variables and Constants ------------------------------------------------------------ 21Variable declaration ------------------------------------------------------------------------------------ 23
Instructions ---------------------------------------------------------------------------------------------- 27
Control Logic Structure-------------------------------------------------------------------------------- 35Sequence ------------------------------------------------------------------------------------------------- 36
Selection ------------------------------------------------------------------------------------------------- 38
Iteration -------------------------------------------------------------------------------------------------- 43The for loop --------------------------------------------------------------------------------------------- 54
Algorithm Checking Method ------------------------------------------------------------------------- 55Quiz------------------------------------------------------------------------------------------------------- 57
Solved Examples------------------------------------------------------------------------------------------ 58
Programming Logic and Techniques
Program Development Life Cycle Algorithm Development
Arrays Problem Solving
Programming Logic Technique
Program Development Life Cycle Algorithm Development
Problem Solving
8/8/2019 PLT YSM Pro
5/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 5
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 TechniquesState 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 structureAppreciate iteration
Appreciate the various algorithm-checking methods
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
8/8/2019 PLT YSM Pro
6/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 6
Introduction
Computer is the most exciting invention of the twentieth century. Now a days computersare used in most operations, starting from a simple task like writing a letter to performingcomplex task like Launching a Rocket.
In todays life, we do not have the luxury to take an inordinately long time to perform aparticular 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 beperformed 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 thepower to think. The onus is then on us to brief this machine (computer) about the stepsfor solving a particular problem.
For example, in order to add two numbers, we have to specify instructions to carry out theoperation. Such instructions are known as program.
In other words, we can say that a sequential set of instruction given to the computer tosolve a problem is called a program.
Problem solving in a computer is a step-by-step (systematic) process. There are basicallythree 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.
Introduction
A computer program can be defined as a seriesof 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
8/8/2019 PLT YSM Pro
7/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 7
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
8/8/2019 PLT YSM Pro
8/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 8
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 programmingprocess. 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 aboutascertaining what the problem is.
Suppose we have to automate the payroll process of an organization. In sucha 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 supposedto do- determining its output and the precise inputs needed to solve theproblem.
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
8/8/2019 PLT YSM Pro
9/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 9
Thus, the Requirement Analysis for automating the payroll process wouldinvolve 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, wetry to obtain a solution to the problem.
The first step for this is preparing a logical model based on which the program is to bedeveloped. We represent the logic with the help of a series of instructions, which isknown as algorithm. An Algorithm is a set of instructions required for solving a specificproblem. 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 languageand 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 somerules to ensure that our communication is effective. Computer languages are nodifferent. 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 writtenand 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 seriesof zero (0) and one (1)- popularly known as machine code. Now the program that hasbeen written is required to be converted to machine code to make the computerunderstand what has been written. For that a compiler or an interpreter is useddepending 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 fedto the Compiler. The compiler reads all the code and then converts to anexecutable form that the computer understands.
.Interpreted: In an interpreter based language the program is written and thenfed to the Interpreter. Interpreter reads a line, executes then goes forward, andreads 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.
8/8/2019 PLT YSM Pro
10/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 10
These errors are:
.Syntactical: This error occurs when an incorrect code is written in a programi.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. Unlikesyntax 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 errorshave been successfully rectified, it is documented.
What is meant by Problem Definition?
8/8/2019 PLT YSM Pro
11/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 11
Structured Programming Techniques
Earlier, programming was confined to the desired output only. A programmer wassatisfied if the program they developed could accomplish its tasks within a reasonabletime frame.
However, they were not concerned about the future- whether or not that program wouldbe equally effective after years. This attitude of the programmers soon resulted indifficulties regarding the future modifications of the program. Every computer programrequires periodic modificationto accommodate changing conditions and requirements.
Since the early programs were not properly pre-structured for periodic modification, itproved tedious to modify them later. Therefore, many a times existing programs wererewritten from the scratch. However, rewriting programs from the scratch resulted inconsiderable wastage of time and effort.
In order to avoid such difficulties, programmers started paying more attention to themanner in which the programs were written. The approach adopted for this purpose isknown as Structured Programming Technique.
Structured Programming Technique is a method of writing programs aiming for notonly the desired solution, but also ensuring that the program logic is clearlyunderstandable to others (future generations).
Structured Programming Techniques
A structured program improves thereadability of the program and make it
more presentable.
A structured program makes use of thefollowing tools:
Subprograms or functions
Comments
Loops
8/8/2019 PLT YSM Pro
12/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 12
This technique has certain features that facilitate clear understanding of the programlogic. One of its features is the concept of Subprograms. Very often, we come across aprogram, which is quite long.
Naturally, as it is much easier for us to break down a huge task into smaller ones andthen 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 ofthe program reads the program, it will be easier for him to understand it. The number ofcomments to be inserted in a program depends upon the complexity of the program.
What is meant by Structured Programming?
8/8/2019 PLT YSM Pro
13/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 13
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 maybecome costly for the software industry.
Hence in all cases if after solving a program we ask the following questions then theprobability 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 everystage of program design.
As discussed, the first stage is understanding program specification. Now after theprogram specification is clear to the developer he draws the flowchart for the program.
Why Documentation is required?
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?
8/8/2019 PLT YSM Pro
14/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 14
Flowchart
A flowchartis 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 andother relevant information pertaining to a particular problem.
There are two types of flowcharts:
System Flowchart- This is normally used to describe the data flow andoperations for a data processing cycle (IPO).
They show the origin of data, the processing to be performed and the output tobe 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, whichprovide a clear understanding of the algorithm used.
What is the difference between a System Flowchart and a Programflowchart?
Flowchart
Flowchart is the symbolic representation of a program.
Flowcharting Components are:Start/Stop
Input/Output
Decision
Action/Predefined Process
Connector Symbol
8/8/2019 PLT YSM Pro
15/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 15
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?
8/8/2019 PLT YSM Pro
16/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 16
First Flowchart
Let us now develop our first flowchart that displays a message.
Start
Display This
is my first
flowchart
Stop
8/8/2019 PLT YSM Pro
17/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 17
Advantages of flowchart
Easy understandability:
By viewing a flowchart, a person can easily understand the problem for which theflowchart is drawn even if the person has not drawn the flowchart.
Pictorial representation:
As discussed it is a pictorial representation and some predefined symbols areused for that. Now as the symbols are predefined, it makes clear what for theflowchart 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 notbefore writing the program in any language. We can see the flow of data in theflowchart, as it is a pictorial representation of a program.
Language independent:
Flowchart is not dependent on any language. It just follows some symbols andsimple English. After drawing the flowchart, it can be converted to anyprogramming language like C, C++, Java, etc.
Advantages of Flowchart
Easy understandability
Pictorial representation
Clear view of logical data flow
Language independent
8/8/2019 PLT YSM Pro
18/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 18
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 inany programming language.
As discussed in the previous chapter algorithm is the first step towards developing aprogram. It provides the programmers with a detailed blueprint with regards to thesolution of a problem. This blueprint is then converted into a full-fledged program writtenin a particular programming language.
Algorithm
Algorithm is a series of instructions that areissued 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
8/8/2019 PLT YSM Pro
19/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 19
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 theefficiency of an algorithm.
As we have already discussed about the flowchart in the previous chapter now letsdiscuss about Pseudocode.
8/8/2019 PLT YSM Pro
20/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 20
Pseudocode
A Pseudocode is the text representation of a Flow Chart in simple English. It is a goodpractice for a beginner to first write a Pseudocode and then transforms the same to anyprogramming language.
One can also substitute the Pseudocode with a Flow Chart but the former is handy whensolving the logic for a large program. This is because in all the modern programminglanguages instructions are issued in English-like statements. Therefore, the developersare 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 typeto 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 previouschapter:
Begin
Display This is my first Flowchart;
End
Pseudocode
A Pseudocode is text representation of a Flow Chart in
simple English, devoid of any programming languagesyntax.
8/8/2019 PLT YSM Pro
21/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 21
Introduction to Variables and Constants
By now, its clear that to develop an algorithm we require data. For example, to create analgorithm 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 valuesthroughout 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 Symbolssuch 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 bedefined as a series of Alphanumeric Character Constants.
For example, India and A009 are Stings.
A Variable is a memory location which can have
changeable values in a program.There are threetypes of variables Alphanumeric Numeric String
A Constant has a definite value in a program.AConstant is of two types:
Alphanumeric Constants Numeric Constants
Every variable or constant has a name & datatype.
Introduction to Variables and Constants
8/8/2019 PLT YSM Pro
22/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 22
While representing Strings or Alphanumeric Characters in an algorithm, it is a goodpractice to enclose the alphanumeric character constant within a single quote and analphanumeric String constant within double quotes.
Let us now prepare a Pseudocode to display an Alphanumeric String constant.
BeginDisplay 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 valuessuch 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 featureof 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 analgorithm. We know that data is stored in the memory of a computer. Therefore, toaccess 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 suchlocation.
Suppose, we have to multiply two and four and display the result. Once the numbers aremultiplied and the product is displayed, the result is lost forever from the memory of thecomputer.
Now, if there is a need to use this product in any further calculations, we have to againperform the multiplication. This will result in a duplication of efforts, which is not a healthypractice. 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 numericdata. Numeric variables can either be Integer variable and a Float variable..
8/8/2019 PLT YSM Pro
23/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 23
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 aregoing to be used in a particular program. This is required because the amount of memoryspace required for storing an alphanumeric variable is different for that required to store aNumeric variable.
When a variable stores an Alphanumeric value, it cannot be used for performing anycalculations. Thus, if we declare a variable as alphanumeric, the computer knows that thevalue 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 inthe 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 Stringvariables, the declaration is:
character address[10];
In the above example, the String variable address can store upto 10 characters.
Variable Declaration
Variables should be declared before they are used in aprogram
Variable is declared in the following mannerdata type varaiable_name
A String variable should be declared in the followingmanner:
data type varaiable_name [size]
Values can be assigned to the variables either at thetime of its declaration or any time after that.
8/8/2019 PLT YSM Pro
24/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 24
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 theassignment of values to variables. In a program, we can assign values to variables in thefollowing 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 itthe value Smith. The following code snippet shows us how to declare and assign valuesto 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 bedone in the following manner:
character name[10]
name = Smith
Let us now see a complete program wherein we shall display the values assigned to analphanumeric, numeric and a float variable.
Begin
character name
integer number = 10
float quantity = 10.22
name = Ram
Display name
Display numberDisplay quantity
End
8/8/2019 PLT YSM Pro
25/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 25
Let us now prepare a Flowchart depicting the above Pseudocode.
The = symbol in the program is called assignment operator and is used for assignment ofvalues 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 rememberthat the name given to a variable should be meaningful and should briefly describewhat the variable stands for in the program. For example, a variable that is used tostore 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 avariable that is used to store the name of a student as address, it is not easy foranyone reading our program to understand what this variable does
We cannot give an identical name to two variables. For example, if we store thenames of two students in two variables, then we have to give two different names tothese variables even if they store the same type of data.
Start
=
Declare number = 10
Declare uantit = 10.22
Stop
Display name
Display number
Display quantity
8/8/2019 PLT YSM Pro
26/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 26
It is a good practice to ensure that the first letter of a variable is an alphabet and thesubsequent letter can be alphabets or digits. For example, we cannot name a variableas 9ABC. However, we can definitely name the variable as A9BC or ABC9.
Every programming language has some words that are used to instruct the computersto 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 cannotname a variable as cin. Therefore, we can safely assume that keywords cannot beused as variable names.
The variable naming rules given above are general and more or less apply to everyprogramming language. However, there are various other programming namingconventions which vary from program to program.
8/8/2019 PLT YSM Pro
27/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 27
Instructions
Instructions are executable lines in a program. A single line is called a statement. It cancontain command, variables and constants. For example, at the time of declaration of avariable, we use the following statement:
character address = Calcutta
In practice, when we use the above statement, we actually instruct the computer to namea 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 aninstruction.
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 theaddress variable actually involves the combination of a command, Display and a variableaddress.
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.
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 InstructionsInput/Output InstructionsOperators:Are of the following three types
Arithmetic Relational Logical
Control Instructions
8/8/2019 PLT YSM Pro
28/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 28
2. Input/Output instructions: Theseinstructions are used to perform input and outputoperations. For example, to multiply two numbers, we have to supply the numbers asdata inputs.
When the product of the two numbers are displayed to the user, it is known as dataoutput.
We have already seen in earlier examples that for displaying any information to theuser, 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 nowstudy an algorithm that accepts the name of the user and thereafter displays theusers name.
The flowchart for the above problem is as follows:
Start
Accept name
Declare name
Display Enter name
Display name is:"
Display name
Sto
8/8/2019 PLT YSM Pro
29/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 29
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 commandis 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 isdisplayed using the Display command.
3. Operators: The algorithm that we have prepared above merely accepted inputs fromthe users and then displayed them. However, computer programs can do much morethan that.
A computer can perform simple and complex computations, compare the relationshipbetween 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 withcertain 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 variousarithmetical calculations.
Operations Symbols
Addition +
Subtraction -
Multiplication *
Division /
Modulous %
The above symbols are called arithmetic operators. Modulo operator returns theremainder when we divide one integer with another.
8/8/2019 PLT YSM Pro
30/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 30
Examples:
1. In the algorithm below, we shall try to find out the average of three numbers afteraccepting the numbers from the users.
The flowchart to solve the problem is:
Start
Declare num1,
num2, num3, result
Accept num1
Accept num2
Accept num3
result = (num1 + num2 + num3)/3
Display Enterthe first number
Display Enter the
second number
Display Enter the
third number
Display result
Stop
8/8/2019 PLT YSM Pro
31/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 31
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 numberAccept 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 acceptingthem from the user.
The flowchart and Pseudocode for this problem is as follows:
Start
Declare num1, num2, result
Accept num1
Acce t num2
result = num1 % num2
Stop
Display Enter
the first number
Display Enter thesecond number
Display result
8/8/2019 PLT YSM Pro
32/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 32
Following is the Pseudocode for the above problem:
Begin
integer num1, num2, result
Display Enter the first number
Accept num1
Display Enter the second numberAccept num2
result = num1 % num2
Display num2
End
3. Let us consider another example of an arithmetic operator. The Flowchart givenbelow accepts the item name, rate and quantity from the user and displays theprice (rate * quantity).
Start
Declare item name uantit rate rice
Acce t item name
DisplayEnter item
Display Enterquantity
Acce t uantit
Display
Enter rate
Accept quantity
price = quantity * rate
Display price
8/8/2019 PLT YSM Pro
33/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 33
Following is the Pseudocode for the above problem:
Begin
character item_name[10]
integer quantity, rate, price
Display Enter the name of the itemAccept 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 valueof one variable with a constant.
For example, we can use Relational operators to ascertain whether a particularvariable is equal to, greater than another variable, or constant.
Every programming language provides the user with the following Relationaloperators:
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
8/8/2019 PLT YSM Pro
34/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 34
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 equalto 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 thefollowing manner:
(number == 10 and number1 > 20)
Normally, Logical operators return a True or False indicating whether the checkinghas 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 theabove example, the condition evaluates to True if the value of the number variable isequal 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 thevariable 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 returnsTRUE,then the NOT converts it to false and vice-versa.
4. Control Instructions: The control instructions determine the flow of control in aprogram. They determine the order in which the various instructions in a program areto be executed.
We shall learn more about ControlInstructions in the subsequent sections.
8/8/2019 PLT YSM Pro
35/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 35
Control Logic Structure
In 1968, Dijkstras a computer guru, opened a new horizon in the field of computerprogramming.
Earlier, when there was a need to skip certain instructions and go to a particular set ofinstructions, programmers used GOTO to achieve this particular task. GOTO had itsorigin in the Assembly equivalent JUMP and programmers thought it to be indispensablein writing large programs.
However, Dijkstras article clearly stated the disadvantages of GOTO giving a newalternative definition of Structured Programming Language. According to him, only threetechniques are to be used namely Sequence, Selectionand Iterationto successfully writeprograms of any size.
Gradually in 1975, Jacksons Structured Program came up followed by the Warnier-Orrmethodology, which were subsequently replaced by other techniques.
The flow of a flowchart depends upon the problem, which you are solving. The controllogic structure of the flowchart may be Sequential or Selection or Iteration.
Now lets discuss broadly the three control logic structures.
Control Logic Structure
There are three types of Control Logic Structurenamely:
Sequence Selection
Iteration
8/8/2019 PLT YSM Pro
36/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 36
Sequence
Sequence is a programming technique where a particular program contains a series ofinstructions and each instruction is executed one after the other. All the instructions are tobe executed at least once for the complete execution of the program. If any step ismissed, we shall not be able to achieve our desired result.
We have already seen examples of sequential programming in the algorithms andcreated in the preceding sections. However, in order to refresh our memory let us createanother algorithm involving sequential instructions.
In the example below, lets create a Flowchart that adds two numbers and displays the
result.
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 toachieve the desired result.
If a particular step is omitted then the required output
cannot be achieved
8/8/2019 PLT YSM Pro
37/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 37
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 toexecute each of the above steps in a sequential manner i.e., one after the other. If any ofthe steps are missed, we shall not be able to achieve our goal.
8/8/2019 PLT YSM Pro
38/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 38
Selection
In the case of selection, unlike a sequence, the statements jump from one point to theother depending on a specific criterion. Selection is used when we have to take differentcourses of actions depending upon certain criteria. If a particular criterion is met, weexecute a particular set of instructions. Otherwise, we execute another set ofinstructions..
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 basedon certain conditions. Each If statement ends with an Endif statement in most of thelanguages.
Many a times when we take a decision, we also think of the possible alternative course ofactions. The Else statement provides another course of action when the given conditionis not satisfied. The statements after the Else statement are executed only if the conditionwritten with If is not satisfied.
In other words, if the condition evaluated by the If clause is satisfied, the instructionsfollowing the If clause are executed. If the condition evaluated by the If clause is notsatisfied, 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, wehave to develop a program where we allow an individual to vote and if his age is 18 orabove. Otherwise, a message is to be displayed informing him that he cannot vote.
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 aPseudocode
In a flowchart decision making is represented by
the symbol given below:
8/8/2019 PLT YSM Pro
39/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 39
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 theage 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 caseswhere 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 instructionsfollowing the if and else within braces (parenthesis).
The flowchart for this problem is given in the next page. In this flowchart, we have usedthe decision box to test the if condition.
Display
Cannot vote
Declare a e
Accept age
If age
>= 18Display
Can vote
Yes
Sto
8/8/2019 PLT YSM Pro
40/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 40
2. Let us take another example where we shall determine whether a particular number iseven or odd.
The Flowchart for above problem is given in the next page.
We all know that a particular number is even if it is divisible by two. Hence, when an evennumber is divided by two the remainder is zero. This remainder is stored in the variableresult.
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 thatthe number is an odd number. Thus, we shall display a message Odd Number.
Stop
No
Start
Declare num,
result
Accept num
Ifresult
== 0
result = num%2
Display Evennumber
Display Oddnumber
8/8/2019 PLT YSM Pro
41/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 41
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 clausewithin an Else clauseor within another If clause.
3. Let us consider an example to find the largest number among three different positivenumbers.
The flowchart for the above example is in the next page:
8/8/2019 PLT YSM Pro
42/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 42
In the above flowchart, we have accepted three numbers from the users and stored themin 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 xis largest number. But, if variable x is less than variable y, then we compare variable ywith 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
8/8/2019 PLT YSM Pro
43/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 43
Iteration
This logic structure is used when we need to repeat some steps within a program. In aprogram, there can be situations where we have to execute a series of instructionsrepeatedly.
In computer terminology, these sets of instructions are kept within a loop. The loopconcept helps in cutting down the code size.
Say, we have to write a program to display hundred numbers. Without the concept oflooping, we have to develop the code (for accepting and displaying the numbers) 100times- a massive task.
With the help of loops, we can place the instructions to be repeated in one particularplace.
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
DoWhile Loop This is executed at least once and for subsequenttimes if the condition remains true.
For loop - This loop also executed a set of statements depending oncertain condition. It has three parts.
Iteration
This logic structure is used when we need to repeatsome steps within a program.
An entire cycle of repetition is called a loop. The 2 most
common varieties are:
While
Do..while
For loop
8/8/2019 PLT YSM Pro
44/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 44
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 mustbe declared and initialized. A counter is a variable that isincremented/decremented each time the instructions within a loop isexecuted (elucidated later).
2. Loop Condition The condition based on which the iterations will occur3. Loop Counter Increment/Decrement Change the loop counter
appropriately before going for the next iteration as this may later lead toinfinite or non-terminating loops.
The repetitive tasks written within the loop constructs (Do. Enddo) make up the body ofthe loop. However, we must ensure that a loop has a terminating condition.
In Do..While Loop, the statements within the loop must be executedat least once, but in While loop, it may be even None; because inDo While Loop, the condition is checked at the end whilst in While
loop, the condition is checked in the beginning.
Iteration (Contd.)
A loop has 3 critical points
Loop counter initialization
Loop condition
Loop counter increment/decrement
8/8/2019 PLT YSM Pro
45/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 45
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, thenonly the instructions specified in the body of the loop are executed. In a While loop, thecondition is evaluated after each iteration. The body of the While loop is executed as longas this condition is satisfied.
However, if the loop condition is not satisfied, the body of the loop will not be executed atall.
Example:
1. Lets display a series of numbers from 1 to 100.
The pseudocode for this problem is as follows:
Begin
integer x = 1
While (x
8/8/2019 PLT YSM Pro
46/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 46
The flowchart for the problem is as follows:
2. Let us consider another example where we shall accept a number from the user andgenerate 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 = 1Accept x
While (y
8/8/2019 PLT YSM Pro
47/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 47
Yes
Start
Declare x, y, z
= 1
Accept x
Is
y
8/8/2019 PLT YSM Pro
48/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 48
Iteration (Contd.)
The body of the While loop may not be executed at all if the loop condition is notsatisfied.
However, we may have to face a situation where the loop body is to be executed at leastonce, irrespective of the fact whether or not the loop condition is satisfied. In order to helpus in such circumstances, most programming languages support a special kind of loopknown 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 to100. But, this time we shall solve this problem with the help of a Do..While loop. Theflowchart for this is as follows:
Iteration (Contd.)
In a do.. while loop the loop condition is
evaluated to TRUE after the loop body gets executedat least once
8/8/2019 PLT YSM Pro
49/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 49
From the above flowchart, we can see that the variable x is displayed once before theWhile loop condition is evaluated. Thus, even if by mistake, we initialize the variable x to101, 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 than100, 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
8/8/2019 PLT YSM Pro
50/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 50
The Pseudocode is:
Begin
integer num, result, ctr, total
c t r = 0
total= 0While (ctr < 5)
{
Display Enter a number
Accept num
result = num % 10
If (result == 0)
{
total = total + 1
}
Endif
c t r = c t r + 1
}
Display total
End
8/8/2019 PLT YSM Pro
51/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 51
The flowchart for the above program is :
Yes
No
No
Start
Declare num, result,
ctr, total
ctr = 0
total = 0
Accept num
Is
ctr < 5
result = num %10
Is
result == 0
total = total + 1
Display Enter a
number
Display
total Stop
ctr = ctr + 1
8/8/2019 PLT YSM Pro
52/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 52
Let us now find out the highest value among hundred positive numbers entered by theuser.
The Pseudocode for this is:
Begininteger num, ctr, max
c t r = 0
m a x = 0
While ( ctr max)
{
max = num
}
Endifctr = ctr +1
}
Display max
End
In the above Pseudocode, we are initializing a variable called max with 0. The numberthat is entered is compared with max.
If the number entered is greater than max, we assign this number to max. This process iscontinued until the value of ctr is equal to 100.
The flowchart for the above problem is as follows:
8/8/2019 PLT YSM Pro
53/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 53
No
ctr = ctr + 1
No
Start
Declare num, ctr,
max
ctr = 0
max = 0
Accept num
Is ctr max
max = num
Yes
Display
Enter a number
Display
max
Yes
Stop
8/8/2019 PLT YSM Pro
54/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 54
The for loop
The for loop executes a set of statements for certain number of times until the condition ismatched.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
The for loop
The for loop executes a set of statements for certainnumber 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 thevalue of variable
8/8/2019 PLT YSM Pro
55/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 55
Algorithm Checking Method
In order to check whether the Algorithm we have developed gives the desiredoutput 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. Inthis method, a table is prepared with columns for each variable used in thealgorithm. The value of each variable is updated in the table as we proceed throughthe 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
Algorithm Checking Method
Checks the correctness and validity of analgorithm. The following are the three types ofAlgorithm Checking Method:
Dry Run
Independent Inspection
Structured Walk-through
8/8/2019 PLT YSM Pro
56/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 56
Dry Run Table
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 arehandled. Inspection or dry run checks the solution.
This method must be adopted as it brings objectivity in the design of the algorithm. Theperson who has developed the algorithm shall always view it with a bias and may notforesee situations that may arise, other than those already taken care of. While a personwho 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 analgorithm 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 errorsbecomes easier while explaining the logic to others.
The solution is either accepted completely, or accepted after minor modifications, orrejected completely. It is more productive than a dry run or an independent inspection.
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
8/8/2019 PLT YSM Pro
57/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 57
Quiz
Answer the following in brief:
1. Define an Algorithm, a Flow Chart and a Pseudocode2. 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,510. Prepare a Flowchart that will accept 50 numbers from the user and find the
minimum one from among these numbers.
Quiz
8/8/2019 PLT YSM Pro
58/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 58
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 acount of the number of students that passed the examination. A pass is awarded for allmarks of 50 and above.
The algorithm is as follows:
.Start
.Prompt the user for the number of students whose marks have to beprocessed.
.Declare a variable count and initialize it to 0.
.While the Value of count is equal to or less than the user input, read themarks 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
8/8/2019 PLT YSM Pro
59/60
Programming Logic and Techniques
SR/PLT/301/0102/SC/2.0 59
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 inthe 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 indicatewhether 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 thanzero, 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 followingsteps to be followed:
8/8/2019 PLT YSM Pro
60/60
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 valuestored 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,nn=0
t1=1
t2=1Display t1,t2
While(n
Recommended