PST Notes
PST Notes
TEXT BOOK:
Stewart Venit, “Introduction to Programming: Concepts and Design”, Fourth Edition,
2010, Dream Tech Publishers.
2
UNIT I
Introduction: History, characteristics and limitations of Computer.
Hardware/Anatomy of Computer: CPU, Memory, Secondary storage devices, Input
Devices and Output devices. Types of Computers: PC, Workstation, Minicomputer,
Main frame and Supercomputer. Software: System software and Application software.
-------------------------------------------------------------------------------------------------------
DEFINITION: A computer is a mechanical or electronic device that can efficiently
store, retrieve and manipulate large amounts of information at high speed and with
great accuracy. It can execute tasks without human intervention by carrying out a list
of instructions called a program. The evolution of computers has been distinctly
divided into five generations. The various application areas of computers are
education, business, communication, science, engineering, entertainment, banking,
health etc.
HISTORY OF COMPUTERS
operating speed, restricted computations, high power consumption, short mean time
between failures, very large space requirements etc.
In 1955, about 300 computers were built by IBM and were used largely by
businesses, universities and government agencies.
Computers later became significantly faster and reliable as large and heat producing
vacuum tubes were replaced by small transistors. Due to their low energy needs,
cheapness and small size, they can be packed closer in a compact design. Another
major event is the invention of magnetic cores used to build RAM. The increased
reliability and availability of large memories paved the way for the development of
high level languages (HLL) like Fortran, COBOL and new operating systems.
In early 1960s, DEC (Digital Equipment Corporation) took feature of small,
efficient packages of transistors called as Integrated Circuits (ICs), popularly
known as chips to create minicomputer, which are smaller and also cheap in
price. IC is wafer thin slice of extremely purified silicon crystals. A single IC
encloses many transistors, resistors and capacitors along with the associated
circuitry. So computers using ICs are highly reliable, relatively inexpensive and
faster and use less human labor.
Later mainframes come into existence.
In 1970s, computers have become a house hold appliance. This was achieved by the
invention of microchip, a piece of silicon about a size of a stamp but can hold
numerous components within it.
In 1974, the cousin of microchip came into existence called microprocessor, after
which actual PC (Personal Computer) arrived. The emergence of microprocessor
led to extremely powerful PCS, increased memory capacity (secondary memory
with high storage) with invent of powerful OS. It was a relatively inexpensive
machine, small enough to fit on a desktop. PC attracted many professionals and
hobbyists. In 1977, a better and more useful computer APPLE II came. In 1981,
IBM brought widely popular IBM PC which assured the future of PC. Computer
networks, simulation, multimedia, parallel computing and virtual reality came into
existence.
IBM threw out Macintosh and accounted 95% of PC market in 1984. IBM relayed
on MS Windows OS for its operations which includes word processors, photo
editing programs, web browsers and a few computer games.
Now many PCs from IBM, Dell, Gateway, Compaq, Acer, Samsung etc are in the
market.
Supercomputers are even more powerful than mainframes and can process over one
billion instructions per second. Now there are devices that respond to natural
language input and are capable of learning and self-organization. This generation
computers have the ability to classify information, search large databases rapidly,
plan, apply the rules which humans regard as clear thinking, make decisions and
earn from their mistakes.
4
Among all improvements for the last 10 years in IT industry, the Internet stood
first. The Internet is a world-wide collection of networks, interlinked computers
that are able to share resources and data via cable or phone lines.
The two main attractions of Internet are
WWW (World Wide Web) is a vast collection of linked documents
(web pages) created by Internet users and stored on thousands of
Internet-connected computers.
E-Mail (Electronic Mail) allows anyone with access to the Internet to
use computer to exchange messages with little or no cost with another
Internet user anywhere in the world.
Most computers today use the idea of stored program computer that was
proposed by Dr. John Van Newmann in 1945. The Von Newmann architecture is
based on three key concepts that are:
Data and instructions are stored in a single read-write memory.
The memory contents addressable by locations.
Execution takes place in a sequential fashion (ie) from one instruction
to the next unless modified explicitly.
CHARACTERISTICS OF COMPUTER
1. Speed: A computer is a fast electronic device that can solve problem in few
seconds. The speed of a computer generally depends upon its hardware
configuration.
2. Storage Capacity: A computer can store huge amount of data in its different
storage area in different formats. Generally there are two storage areas: Main
memory and Secondary memory.
3. Accuracy: A computer carries out operation with great accuracy.
4. Reliability: A computer usually produces results without errors-if error means,
mostly there are human generated and so they are trustworthy machines.
5. Versatility: They can perform many different tasks for different purposes.
6. Diligence: Computers can perform repetitive calculations any number of times
with the same accuracy.
7. They don’t suffer from tiredness, fatigue, lack of concentration.
LIMITATIONS OF COMPUTER
Although a computer is far better in performance than a human being, it fails in
certain ways as follows:
(i) Computers cannot think and they can’t do any job unless they are first
programmed with specific instructions for same. They work as per stored instructions.
Algorithms are designed by humans to make a computer perform a special task.
5
(ii) Computers are incapable of decision making as they do not possess the essential
elements necessary to take a decision i.e. knowledge, information, wisdom,
intelligence and the ability to judge.
(iii) Though computers are helpful in storage of data and can contain the contents of
encyclopedias even, but only humans can decide and implement the policies.
(iv) Although the trend today is to make computers intelligent by inducing artificial
intelligence (AI) in them, they still do not have any decision-making abilities of their
own. Thus, their IQ level is zero. They need guidance to perform various tasks.
(v) Overall, a computer was built by humans and new technology comes out all the
time. Hardware will eventually fade out and deteriorate.
HARDWARE/ANATOMY OF COMPUTER
A Computer must have the ability to input, store, manipulate and output data. These
functions are carried out by the five main components of a computer system:
CPU (Central Processing Unit)
Internal Memory (RAM and ROM)
Mass storage devices (Disk Drives)
Input devices
Output devices
Components used by a computer but located outside the system unit are called as
Peripherals. All the physical equipment that makes up the computer system is known as
Hardware.
3. INPUT DEVICES: An input unit is an electronic device which is used to feed data
and control signals to a computer-they are connected to computer using cables. Eg:
Keyboard, Mouse, Scanner, Trackball, Light pen, Joystick, OCR, Digital Camera.
Keyboard: Keyboard is the most common input device used by more users. The
classification of keys are:
a. Function keys perform a specific task such as searching a file or
refreshing a web page.
b. Modifier keys are shift and control keys used to modify the casing
style of a character or symbol.
c. Cursor-movement keys are up, down, left and right keys which are used to
modify the direction of the cursor on the screen.
d. Spacebar key shifts the cursor to the right by one position.
e. Numeric keypad holds numbers and operators.
Mouse: Mouse allows the user to select elements (tools, icons, buttons) by pointing
and clicking them. Mouse can be used to draw and paint on the screen. It is called
as Pointing Device because it is used to change the
8
position of cursor. Mouse has two buttons, a wheel on the top and a ball at its base.
Scanner: It is used to convert documents and images as the digitized images
understandable by computers-the digitized images can be black and white or colour.
Proportion of red, green, blue will determine the colour proportion.
TYPES OF COMPUTERS
Computers can be broadly classified by their speed and computing power.
It is a single user computer system having
PC (Personal Computer)
moderately powerful microprocessor.
It is also a single user computer system,
Workstation similar to personal computer with more
powerful microprocessor.
It is a multi-user computer system, capable of
Mini Computer
supporting many users simultaneously.
Main Frame It is a multi-user computer system, capable of
9
scientific, industrial and business environments that require high levels of computational
abilities.
5. Supercomputer: Supercomputers are one of the fastest computers and the most
powerful among digital computers. They consist of several processors running
together thereby making them faster and powerful. Supercomputers are very expensive
10
SOFTWARE
Software refers to a set of computer programs that are required to enable the hardware
to work and perform these operations effectively.
1. SYSTEM SOFTWARE: Depending upon the task performed, the system software
can be classified into two:
System Management Programs enable the users to perform certain utility
functions like creating backup files, recovering damaged files and merging files.
They minimize the human intervention during processing and help in maximizing
productivity of a computer system.
Eg: Operating system, Utility programs, Device drivers
12
Syntax:
[label] <opcode> <operands> [;comment]
Eg: ADD
A,B
Functions of an assembler:
1. Allows the programmer to use mnemonics and symbolic names in writing
source codes.
2. Checks the syntax of assembly program and generates error messages or
syntax errors.
3. Translates mnemonics to operation code.
4. Translates the register names to system address.
5. Assembles all the instruction in the main memory for execution.
6. Provides linking facility among the subroutines.
7. Generation of output on required output medium.
The primary register for all operations is accumulator (A). One of the
operands should be at A, the process is carried out at A and the result is also stored
at A.
Advantages:
Easy to understand and use.
Less error prone
Efficiency (fast and use less memory)
More control over hardware
Disadvantages:
-Machine dependent.
-Slow development time.
-Harder to learn.
-No standardization.
3. HIGH LEVEL LANGUAGE (HLL) usually contains English words and phrases. A
single instruction in HLL usually translates into many instructions in machine
language. A HLL program must be translated into machine language as they should
be understood by a computer. HLL have several advantages over machine and
assembly languages as,
+HLL is easier to learn and use as they are closer to natural languages
+Resultant programs are easier to read and modify
+ A given HLL doesn’t differ very much from computer to computer
+ HLL permits faster development of program in lesser cost
+HLL is useful in developing complex software as it supports many
complex data structures
+The programmer doesn’t need to learn the instruction set of each computer
(machine independent)
+HLL supports the ideas of abstraction so that the programmers can
concentrate on the solution rather than on lower level details.
18
4. 4GL are non-procedural languages which are commonly used to access the
databases (ie) the computer is instructed what rather than how. They are easier to
write, but the user does not have any control over it. With increase in power and
speed of hardware and with diminishing costs, the use of 4GLs has spread. The
components of 4GL are query languages, report generators and application
generators. The advantage of 4GL is shorter development and debugging time
while requirement of more disk space is its demerit.
5. 5GL can process natural languages (ie) they can accept, interpret and execute
instructions in natural languages. So the user will be free to learn any programming
language. 5GLs are closely related to artificial intelligence and expert systems.
3. Naturalness for the application-The language should have a syntax which allows
the program structure to show the underlying logical structure of algorithm or
flowchart (ie) promote structural programming.
4. Reliability-The language should have the support of error detection as well as
prevention which makes a system failure free.
5. Performance-The application developed by a PL should tap the maximum
performance of available hardware in terms of high speed and efficiency with low
cost.
6. Compact code-Develop the code with minimum number of lines
7. Maintainability- Easy to accept changes
8. Reusability- Facilitate the adoption of code in similar applications.
9. Ability to provide interface to other language.
10. Concurrency support-Extent to which inherent languages support the
construction of code with multiple threads of control (parallel processing).
11. Standardization- Extent to which PL has been supported by recognized bodies
like ANSI, ISO. Non-standard PL will soon become obsolete and surely produce
poor code.
TRANSLATORS
Computers only understand machine code (binary code). To get around the issue,
the high-level and low-level program code (source code) needs to pass through a
translator. A translator will convert the source code into machine code (object code).
There are several types of translator programs, each able to perform different tasks.
Interpreter: Interpreter programs are able to read, translate and execute one statement at
a time from a high-level language program. The interpreter stops when a line of code is
reached that contains an error. Interpreters are often used during the development of a
program. They make debugging easier as each line of code is analysed and checked
before execution. Interpreted programs will launch immediately, but program
may run slower than a complied file. No executable file is produced. The program is
interpreted again from scratch every time the user launches it.
Compiler: System software that stores the complete program, scans it, translates the
complete program into object code and then creates an executable code is called a
compiler. Compilers are used to translate a program written in a high-level language into
machine code (object code). Once compiled, the translated program file can then be
directly used by the computer and is independently executable. Compiling may take
some time but the translated program can be used again and again without the need for
recompilation. An error report is often produced after the full program has been
translated. Errors in the program code may cause a computer to crash. These errors can
only be fixed by changing the original source code and compiling the program again. On
the face of it compilers compare unfavourably with interpreters because they −
are more complex than interpreters
need more memory space
take more time in compiling source code
The steps in compiling source code into executable code using compiler are:
Pre-processing − In this stage pre-processor instructions, typically used by
languages like C and C++ are interpreted, i.e. converted to assembly level language.
Lexical analysis − Here all instructions are converted to lexical units like
constants, variables, arithmetic symbols, etc.
Parsing − Here all instructions are checked to see if they conform to
grammar rules of the language. If there are errors, compiler will ask you to fix
them before you can proceed.
Compiling − At this stage the source code is converted into object code.
Linking − If there are any links to external files or libraries, addresses of their
executable will be added to the program. Also, if the code needs to be rearranged
for actual execution, they will be rearranged. The final output is the executable
code that is ready to be executed.
20
COMPILE INTERPRETER
R
Translates high-level languages
into Temporarily executes high-level
machine code languages, one statement at a time
An executable file of machine code is No executable file of machine code is
produced (object code) produced ( no object code)
Compiled programs no longer need the Interpreted programs cannot be
compiler used without the interpreter
Error report produced once the entire Error message produced
program is compiled immediately and program stops at
that point
Compiling may be slow, but the resulting Interpreted code is run through the
program code will run quickly (directly on interpreter (IDE), so it may be slow
the processor)
DATA
Data is the entity which holds the value that will be manipulated in the program.
There are two fundamental types of data.
1. Numeric data consists of numbers-this type of data is usually subdivided
into integer or floating point data. Integer data refers to whole numbers while
float data refers to the number with decimal point.
2. Character or Alphanumeric data consists of characters-characters usually
enclose within single quotes or double quotes (strings). Special characters
like , : : ! etc is also a valid character.
21
INPUT: The input operation transmits data from an outside source to the program. Often
this data will be typed at the keyboard by the user. There will be a set of input statements
in all programming languages to scan the input.
PROCESSING OF DATA: The read values are now at a and b. They both are summed
up and the value is stored at c. To know the result, the c’s value is displayed.
VARIABL BEFORE AFTE
E R
a 10 10
b 20 20
C Undefined 30
Please note that the values of a and b don’t change even though it appears at the
right side of the statement. But the value of c is undefined when the user gives 10 and
20 to a and b respectively. Therefore in an assignment statement, RHS of the expression
will be computed before LHS.
Let x=100;
22
:
:
x=200;
What happens if a variable that already has a value is reassigned with another
value? In such a case the latest value will overwrite the old value in its memory location
(ie) x holds 200 and not 100.
Operators: They are the symbols which indicate what operation has be done with the
data. The types of operators are:
ARITHMETIC
OPERATORS
Addition +
Subtraction -
Multiplication *
Division /
Exponential ^
RELATIONAL
OPERATORS
Less than <
Less than or equal to <=
Greater than >
Greater than or equal to >=
Equal to +
Not equal to <>
LOGICAL
OPERATORS
AND
OR
NOT
Hierarchy of operations:
1. First perform the operations in parenthesis.
2. Next perform exponentials
3. Do multiplications and divisions from left to right if there is more than one.
4. Finally do additions and subtractions from left to right if there is more than one.
Eg: 3*(6+2)/12-(7-5)^2*3
=3*8/12-2^2*3
=3*8/12-4*3
=24/12-4*3
=2-4*3
23
=2-12
=-10
OPERATORS ORDER OF
EXECUTION
Arithmetic operators First
Relational operators Second
Logical operators Third
OUTPUT: A program’s output is data sent from memory to the screen, printer or to a
file. The output is normally the results of the program’s processing part.
The output of a program can be well understood if they are prompted with some
information. For example, instead of printing the result of sum of 2 numbers ‘c’, it will be
more attractive if we write at display “The sum =”,c. Of course each programming
language has its own output statements to create various kinds of screen. Therefore the
basic building blocks of a program are input, processing and output.
demands. The team of software designers, developers are required to interact with each
other at each stage to bring the end product as per the client’s requirements.
developers. Based on the feedback, the programmers can modify or enhance the program.
i) Maintenance and Enhancement: After the program is implemented, it should
be properly maintained by taking care of the changing requirements of its users and
system. The program should be regularly enhanced by adding additional capabilities. This
phase is also concerned with detecting and fixing the errors, which were missed in testing
phase. Since this step generates user feedback, the programming cycle continues as the
program modified or reconstructed to meet the changing needs.
UNIT III
Structured Programming: Algorithm: Features of good algorithm, Benefits and
drawbacks of algorithm. Flowcharts: Advantages and limitations of flowcharts, when to
use flowcharts, flowchart symbols and types of flowcharts.
STRUCTURED PROGRAMMING
Structured Programming is a method for designing and coding programs in a
systematic, organized manner. Following the steps of the program development cycle,
designing a program in a top-down fashion, using comments to document a program are
some of the examples of structured programming. A well-structured design leads in a
natural way, to well-structured, easy-to-read code. One of the goals of structured
programming is to create a program that is easy for programmers to read and for users to
run.
ALGORITHMS
Definition: An algorithm is defined as a sequence of clear and explicit instructions that,
when provided with a set of input values produces an output and then terminates.
Algorithms are one of the basic tools that are used to develop the problem solving
logic. Algorithms help a programmer in breaking down the solution of a problem into a
number of steps. Corresponding to each step, a program statement can be written.
Algorithms can have steps that repeat or require decision (comparison) until the task is
completed. Different algorithms may be written for a same problem with a different set of
instructions in more or less the same time, space and effort. Algorithms are not computer
programs as they cannot be executed by a computer.
Benefits of algorithm:
1. It is a step-wise representation of a solution to a given problem, which makes it
easy to understand (ie) algorithm uses a definite procedure. It is easier for
programmer to convert it into an actual program.
2. Writing algorithm and program separately simplifies the overall task by dividing
it into two simpler tasks. While writing the algorithm, we can focus on solving
the problem instead of concentrating on a particular language (Reduced
Complexity).
3. It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge (Increased Flexibility).
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
Drawbacks of algorithm:
1. Writing algorithm is time consuming.
2. Difficult to show branching and looping in algorithms.
3. Big tasks are difficult to put in algorithms.
FLOWCHARTS
A flowchart can be defined as the pictorial representation of a process which
describes the sequence and flow of control of information in a process. Flowchart details
the operations/steps in a pictorial format which is easier to understand than reading it in a
textual format. A flowchart can be linked to the blueprint of a building. The flow of
information is represented in a step-by-step form in a flowchart. Flowchart uses different
symbols for depicting different activities, which are performed at different stages of a
problem.
Flowcharts are generally drawn in the early stages of formulating computer
solutions. Flowcharts play a vital role in the programming of a problem and are
28
quite helpful in understanding the logic of complicated and lengthy problems. Once the
flowchart is drawn, it becomes easy to write the program in any high level language. A
flowchart is a must for the better documentation of a complex program.
Flowchart Symbols:
NOTE:
1. Connector: A small, labelled, circular flow chart shape used to indicate a
jump in the process flow. Connectors are generally used in complex or multi-
sheet diagrams.
2. Arrow: used to show the flow of control in a process. An arrow coming from
one symbol and ending at another symbol represents that control passes to
the symbol the arrow points to.
Basic guidelines for drawing a flowchart with the above symbols are that:
All necessary requirements should be listed out in logical order.
The flowchart should be neat, clear and easy to follow so that there should not
be any room for ambiguity in understanding the flowchart.
The flowchart is to be read left to right or top to bottom.
A process symbol can have only one flow line coming out of it.
29
A decision symbol must have two flow lines coming out of it.
Advantages of flowchart:
1. The flowchart is an excellent way of communicating the logic of a program (ie) the
diagrammatical representation of logic is easy to understand. During program
development cycle, the flowchart plays the role of a guide or a blueprint and makes
program development process easier.
2. It is easy and efficient to analyze problem using flowchart.
3. After successful development of a program, it needs continuous timely
maintenance during the course of its operation. The flowchart makes program
maintenance easier.
4. It helps the programmer to write the program code easily since it is easy to convert
the flowchart into any programming language code as it does not use any specific
programming language concept.
5. Appropriate documentation can be made by flowchart.
Disadvantages of flowchart:
1. The flowchart can be complex when the logic of a program is quite complicated.
2. Drawing flowchart is a time-consuming task.
3. Difficult to alter the flowchart. Sometimes, the designer needs to redraw the
complete flowchart to change the logic of the flowchart or to alter the flowchart.
30
4. Since it uses special sets of symbols for every action, it is quite a tedious task to
develop a flowchart as it requires special tools to draw the necessary symbols.
5. It is just a visualization of a program; it cannot function like an actual program.
Example: Largest of 2 numbers-Value1 and Value2
Types of Flowchart:
1. High-Level Flowchart: A high-level flowchart (also called first-level or top-
down) shows the major steps in a process. It illustrates a "bird’s-eye view" of a
process. It can also include the intermediate outputs of each step (the product or
service produced), and the sub-steps involved. Such a flowchart offers a basic
picture of the process and identifies the changes taking place within the process. It
is significantly useful for identifying appropriate team members (those who are
involved in the process) and for developing indicators for monitoring the process
because of its focus on intermediate outputs. Most processes can be adequately
portrayed in four or five boxes that represent the major steps or activities of the
process. In fact, it is a good idea to use only a few boxes, because doing so forces
one to consider the most important steps. Other steps are usually sub-steps of the
more important ones.
2. Detailed Flowchart: The detailed flowchart provides a detailed picture of a process
by mapping all of the steps and activities that occur in the process. This type of
flowchart indicates the steps or activities of a process and includes such things as
decision points, waiting periods, tasks that frequently must be redone (rework), and
feedback loops. This type of flowchart is useful
31
1
for examining areas of the process in detail and for looking for problems or areas of
inefficiency.
3. Deployment or Matrix Flowchart: A deployment flowchart maps out the process
in terms of who is doing the steps. It is in the form of a matrix, showing the
various participants and the flow of steps among these participants. It is chiefly
useful in identifying who is providing inputs or services to whom, as well as areas
where different people may be needlessly doing the same task.
UNIT IV
Pseudocode: Writing a pseudocode. Coding, documenting and testing a program:
Comment lines and types of errors. Program design: Modular Programming. Selection
Structures: Relational and Logical Operators -Selecting from Several Alternatives –
Applications of Selection Structures.
PSEUDOCODE
Pseudocode is a generic way of describing algorithm without referring to any
specific programming language. Analyzing a detailed algorithm before developing a
program is very time consuming. Hence there arises a need of a specification that only
focuses on the program logic. Pseudo means false or imitation. It is used by the
programmer for developing a computer program. Pseudocode is not written in syntax as
per any programming language, rather written in normal English language using certain
standard program constructs. Hence it is an artificial and informal language that helps
programmers to develop algorithms.
Guidelines:
For looping and selection, the keywords that are to be used include Do
While...EndDo; Do Until...Enddo; Case...EndCase; If...Endif; Call ... with
(parameters); Call; Return ; Return; When;
As verbs, use the words Generate, Compute, Process, set, reset, increment,
calculate, add, sum, multiply, edit, test , etc. with proper and careful indentation
tend to foster desirable pseudocode in order to increase readability.
Output Statements can be represented by write / display / print
Input Statements can be represented by read / get / input
Capitalize initial keyword.
Do not include data declarations in pseudocode. Eg: int x=5;
Use comments wherever necessary.
Always end multiline structures properly.
Write only one statement per line.
Keep statements language independent.
Benefits of Pseudocode:
Easy to understand the program logic.
Implements structured concepts very well.
Developing source code from pseudocode is easy.
31
2
program with various sets of input data (test data) until we are convinced that our program
is working properly.
Types of Errors: If a test run turns up problems with the program, we must debug it-
eliminate the errors. The elimination of error may be easy or difficult depending upon the
type of the error. There are 2 types of errors.
1. Syntax Error: Violation of the programming language’s rules for creating valid
statements is called as syntax error. Eg: Misspelling of keyword, omitting a
punctuation mark. Syntax errors are usually listed after compilation. Usually the
compiler will highlight the error in simple English along with line number-so
syntax errors are easy to find and correct.
2. Logic Error: Failing to use the proper combination of statements to accomplish a
certain task is called as logic error. It may occur due to poor analysis, faulty design,
wrong formula, incorrect sequence of statements, and division by zero etc.
Unlike syntax errors, logic errors are not found by the translator. They can be found
only by a careful reading of program specifications or by running the program with test
data. Certain logic error may lead a program to crash or hang. Hence extensive testing is
the best way to ensure that a program’s logic is sound.
PROGRAM DESIGN
A computer program is basically a set of logical instructions. A program cannot
get the solution of a problem by simply providing input to the computer without preparing
the base for solving the problem. All the activities which have to be performed by a user
in order to solve a problem using computer are grouped into three phases:
1. Identifying the purpose: It is the first stage of problem solving using a computer
which will identify parameters and constraints and collect information relevant to
that.
2. Developing a program: For developing a program a user has to perform the
following activities:
Identifying the logical structure- A user writes algorithm, draw flowchart to
represent the flow of information and writing pseudocode to specify the
programming specifications.
Writing the computer program
Debugging the program
3. Executing the program
31
4
Summary:
1. Write modular programs.
2. Use descriptive variable names.
3. Provide comments for the users.
4. Use prompt before input and output.
5. Document programs.
SELECTION STRUCTURES:
Equal to =
Not equal to ≠
Greater than >
Greater than or equal to ≥
Lesser than <
Lesser than or equal to ≤
Note: ≠, ≥ and ≤ are not available in keyboard. So most programming languages use a
special pair of characters to represent these relational operators.
‘h’!=’B’ true
Eg:
(5>=9) AND (3=3) False
(5>=9) AND (3=3) True
!(3=3)False
X Y X AND X OR NOT NOT
Y Y X Y
true true true true false false
true false false true false true
false true false true True false
false false false false true true
Depending upon the sequence of statements, the control structures can be classified as,
Sequence structures
Selection or Decision structures
Repetition or Loop or Iterative structures
SELECTION STRUCTURES
A selection structure consists of a test condition together with one or more groups
or blocks of statements. The result of the “test” determines which of these blocks is
executed. A selection structure is called
1. A single-alternative or if-then structure if it contains single block of
statements to be either executed or skipped.
2. A dual-alternative or if-then-else structure if it contains two blocks of
statements, one of which is to be executed while the other is to be skipped.
3. A multiple-alternative structure if it contains more than two blocks of
statements, one of which is to be executed while the others are to be skipped.
Syntax: Flowchart:
The test condition or expression will be evaluated first. If its result is true, the
statements enclosed between then and end if will be evaluated. If the condition is false,
the block of statements will be skipped. In both cases of true or false, execution then
proceeds to the program statement following end if.
Eg:
Write “Enter a number:”;
Input n
If (n mod 2=0) then
Write “Number is even”
End if;
If (n mod 2<>0) then
Write “Number is odd”
End if;
Syntax: Flowchart:
If test condition is true, then the block of statements between then and else will be
executed. If the test condition is false, then the block of statements between else and end
if will be executed. In either case, execution then proceeds to the program statements
following end if.
Eg:
Write “Enter a number:”;
Input n
If (n mod 2=0) then
Write “Number is even”
else
If (n mod 2<>0) then
Write “Number is odd”
End if;
Syntax: Flowchart:
If (condition1) then
31
9
Stat A
Else If (condition2) then
Stat B
Else If (condition3) then
Stat C
...............
Else
Body of else
End if
Eg: A program segment that translates a numerical score (represented by an integer from 1 to
10) into a character grade using following rules.
If the score is 10, rating is A
If the score is 8 or 9, rating is B
If the score is 6 or 7, rating is C
If the score is below 7, rating is D
Solution-1: Sequence of if statements If
score=10 then
Set rating=”A”
End if
If (score=8 or score=9) then
Set rating=”B”
End if
Syntax: Flowchart:
default:..............
end case
42
Eg: A program segment that translates a numerical score (represented by an integer from 1 to
10) into a character grade using following rules.
If the score is 10, rating is A
If the score is 8 or 9, rating is B
If the score is 6 or 7, rating is C
If the score is below 7, rating is D
switch (score)
case 10: set rating=”a”
case 8,9: set rating=”b”
case 6,7: set rating=”c”
default: set rating=”d”
end case
Note: To make it easier to read the code for a selection structure, indent the statements that
make up the true and false block.
Else
Write “Don’t enter zero please”
End if
UNIT V
Repetition Structures: Counter Controlled Loops –Nested Loops– Applications of
Repetition Structures. Data: Numeric Data and Character Based Data. Arrays: One
Dimensional Array - Two Dimensional Arrays – Strings as Arrays of Characters.
REPETITION STRUCTURES
All programming languages provide statements to create a loop or repetition
structure-a block of code that, under certain conditions, will be executed repeatedly. The
condition that determines whether a loop is re-entered or exited is usually constructed with
the help of relational and logical operators. All repetition structures can be divided into
two fundamental types: Pre-test loops and Post-test loops.
1. While loop: Here the condition is evaluated first. If the condition is true, the
body of the loop will be executed. Again the condition is checked. The body of the
loop will be executed as long as the condition is true. If the condition is false, the body of
the loop will be skipped. This comes under the category of pre-test loop, since the
condition is checked before the body of the loop. So if the condition is false at the first
time itself, the body of the loop will not be executed at least once.
46
Syntax: Flowchart:
while (condition)
body of the while loop
end while
Eg-1:
Input num While
num>0
Write num^2
Input num
End while
Eg-2:
Set num=1
While num<3
Write 2*num Set
num=num+1
End while
2. Repeat..until loop: Here the body of the loop is executed first. Then the condition
is checked. If the condition is false, the body of the loop will be executed. Again the
condition is checked. The body of the loop will be executed as long as the condition is
false. If the condition is true, the body of the loop will be skipped. This comes under the
category of post-test loop, since the condition is checked after the body of the loop. Even
if condition is true at the first time itself, the body of the loop will be executed at least
once.
Eg-1:
set num=1
repeat
47
write 2*num
set num=num+1 until
num=3
Syntax: Flowchart:
repeat
body of the loop
until condition
Syntax: Flowchart:
Here counter must be a variable, increment must be a constant, initial and final
values may be constants, variables or expressions. On entering the loop, the counter will
be initialized to initial values. If the initial value is not greater than limit value, then the
body of the loop is executed. If counter is greater than limit value, the loop is skipped.
On subsequent pass through the loop, counter is incremented
48
by the value of increment and if the new value of counter is not greater than the limit
value, the body of the loop will be again executed else control goes to end for.
Note: We can also “step backwards” through a loop (ie) increment value can be negative
and here if the initial value is greater than the limit value, the body of the loop will be
executed else not.
Eg-2:
for k=10 step -1 to 1
write k
end for
Eg-3:
write “Before loop”
for k=5 step 1 to 1
49
4. Nested Loops: Programs sometimes employ one loop which is contained entirely
within another-in such a case, the loops are nested. The larger loop is called as the
outer loop and the one lying within it is called as the inner loop.
Flowchart:
Output:
Outer loop iteration 1 i
= 1; j = 1
i = 1; j = 2
Outer loop iteration 2 i
= 2; j = 1
i = 2; j = 2
Outer loop iteration 3 i
= 3; j = 1
i = 3; j = 2
Outer loop iteration 4 i
= 4; j = 1
i = 4; j = 2
Outer loop iteration 5 i
= 5; j = 1
i = 5; j = 2
for i=....
for j=....
for k=....
end for(k)
end for(j)
end for(i)
ote: If a loop’s exit condition is never satisfied, then the loop will never be exited-it will
become an infinite loop. It is therefore important to make sure, through a suitable prompt,
how the user is to terminate the action of the loop.
Write hours,rate,salary
Write “Enter the number of hours worked. Enter -1 to exit”
Input hours
End while
2. Data validation: This refers to the action of getting input continuously until user
enters a valid input. To have the user enter a positive number at some point during
program, we have the pseudocode like this:-
Eg:
Repeat
Write “Input a positive number”
Input num
Until num>0
Here the prompt “Input a positive number” will be printed repeatedly till
the user enters a positive number. If we want to improve the code, we can rewrite
the above pseudocode as,
Write “Input a positive number”
Input num
While num<=0
Write “Number should be positive. Try again” Input
num
End while
So the data validation is an example of defensive programming, writing code
that checks during execution of improper data.
3. Computing sum and averages: These structures are useful in manipulating a large
set of data. We add each successive number to the running total, the sum obtained
so far. We are looping repeatedly applying the addition operation until all the
numbers have been added.
inprotected.com