0% found this document useful (0 votes)
1K views55 pages

PST Notes

The document provides an overview of computer problem-solving techniques, covering the history, hardware anatomy, types of computers, software, programming languages, and structured programming concepts. It details the evolution of computers from early mechanical devices to modern supercomputers, highlighting key components like the CPU, memory, and input/output devices. Additionally, it discusses programming fundamentals, including algorithms, flowcharts, pseudocode, and data structures such as arrays.

Uploaded by

s31286199
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views55 pages

PST Notes

The document provides an overview of computer problem-solving techniques, covering the history, hardware anatomy, types of computers, software, programming languages, and structured programming concepts. It details the evolution of computers from early mechanical devices to modern supercomputers, highlighting key components like the CPU, memory, and input/output devices. Additionally, it discusses programming fundamentals, including algorithms, flowcharts, pseudocode, and data structures such as arrays.

Uploaded by

s31286199
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

1

PROBLEM SOLVING TECHNIQUES

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.

UNIT II: Programming Languages: Machine language, Assembly language, High-level


language, 4GL and 5GL-Features of good programming language. Translators:
Interpreters and Compilers. Data: Data types, Input, Processing of data, Arithmetic
Operators, Hierarchy of operations and Output. Different phases in Program
Development Cycle (PDC).

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.

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.

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.

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

 Charles Babbage designed a computer called “Analytical Machine” in mid-


1800s. It was built with hundreds of axles and gears and could process up to 40-
digit numbers. Unfortunately, Babbage never finished his work since his ideas were
too advanced for the existing technology and also he could not get enough financial
aid for his project.
 In 1945, a team at the University of Pennsylvania completed their work on the
world’s first fully-operable electronic computer called ENIAC-Electronic
Numerical Integrator and Calculator. It can perform 5,000 additions per second
with incredible accuracy. It was 80 feet long, 8 feet high and weighing 33 tons with
17,000 vacuum tubes (thermionic valves) and consumed 1,75,000 watts of
electricity. It was suffered by big limitations like slow
3

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.

1. CENTRAL PROCESSING UNIT: The function of any computer revolves around


CPU-“the brain” of the computer. It controls all other hardware components. The main
operations of the CPU include four phases.
 Fetching instructions from the memory.
6

 Decoding the instructions to decide what operations are to be performed.


 Executing the instructions.
 Storing the results back in the memory.
The three main components of CPU are:
 ALU (Arithmetic Logic Unit): ALU performs arithmetic and logical
operations on the data.
 CU (Control Unit): Control unit controls the flow of data and information. It
maintains the sequence of operations being performed by CPU. CU guides
ALU about the operations that are to be performed and also suggests the I/O
device to which the data is to be communicated. It uses the Program
Counter (PC) register for retrieving the next instruction and Status
Register for handling conditions like overflow of data.
 Registers: Special purpose temporary storage units are called as registers-
PC, IR, MAR, MBR, MDR, AC etc.

2. MEMORY UNIT: The memory unit of a computer is used to store data,


instructions for processing data, and intermediate results of processing and final processed
information. There are two types of memory like Primary and Secondary memory.
 Primary Memory: Primary memory is available as built-in memory. It is
represented as a set of locations with each location occupying 8-bits. The
commonly used primary memories are:
 ROM (Read Only Memory or Permanent Memory) stores data and
instructions even though the computer is turned off. Generally it is used
to store the Basic Input/Output System (BIOS), which performs the
Power On Self Test (POST).
 RAM (Random Access Memory) or Read/Write Memory or Volatile
memory retains the data as long as there is power supply. There is also
SRAM and DRAM in which SRAM is fast and expensive than DRAM.
 Cache Memory is placed between CPU and main memory. It is used to
store the data and related instructions which are often used. Performance
of cache is measured by Hit Ratio.
7

 Secondary Memory: External storage devices with non-volatile memory are


connected externally to the computer.
 Magnetic storage devices store information that can be read, erased
and rewritten a number of times. Eg: Floppy disk, hard disk, magnetic
tapes.
 Optical storage devices use the laser beam to read and write data.
Eg: CD-ROM, CD-RW, DVD-ROM.
 Magneto-optical storage devices have high storage capacity as they
use laser beams and magnets for reading and writing data to the device.
The end-user can modify the data stored for multiple times. Eg: Sony
minidisc.
 USB Drive (Universal Serial Bus Drive) is a removable storage. It is
pretty fast, compact and larger in capacity. Eg: Pendrive.

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.

4. OUTPUT DEVICES: Output unit is an electronic device used to communicate the


output obtained after processing a specific task to the user. Eg: Printers, Monitor,
and Speaker.
 Monitor: Monitor or screen is the commonly used output device that produces
visual presentation of textual and graphical information. The monitors can be
Cathode Ray Tube (CRT) , Liquid Crystal Display (LCD) or Light Emitting Diode
(LED). CRTs are large while LCDs and LEDs are thing and occupy less space. A
monitor can be characterized by its size and resolution. The monitor size is the
length of the screen measured diagonally. Resolution or dot pitch is the number of
picture elements (pixels) per unit square.
 Printer: Printer is used to produce a hard copy of the electronic text displayed on
the screen. The various types of printers are dot matrix printers, inkjet printers and
laser printers. The performance of a printer is measured in terms of Dot Per Inch
(DPI) and Pages Per Minute (PPM).

 Speaker: Speaker is an electromechanical unit that converts electrical signals into


sound. They are used to give warning sounds and internet audio.

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

supporting hundreds of users simultaneously.


Software technology is different from
minicomputer.
It is an extremely fast computer, which can
Supercomputer execute hundreds of millions of instructions per
second.

1. PC (Personal Computer): A PC can be defined as a small, relatively inexpensive


computer designed for an individual user. PCs are based on the microprocessor
technology that enables manufacturers to put an entire CPU on one chip. Businesses use
personal computers for word processing, accounting, desktop publishing, and for
running spreadsheet and database management applications. At home, the most popular
use for personal computers is playing games and surfing the Internet. Although
personal computers are designed as single-user systems, these systems are normally
linked together to form a network. In terms of power, now-a-days high-end models of the
Macintosh and PC offer the same computing power and graphics capability as low-end
workstations by Sun Microsystems, Hewlett-Packard, and Dell. The principal
characteristics of personal computers are that they are single-user systems and are based
on microprocessors. However, although personal computers are designed as single- user
systems, it is common to link them together to form a network.

2. Workstation: Workstation is a computer used for engineering applications (CAD/CAM),


desktop publishing, software development, and other such types of applications which
require a moderate amount of computing power and relatively high quality graphics
capabilities. Workstations generally come with a large, high- resolution graphics screen,
large amount of RAM, more mathematical abilities, inbuilt network support, and a
graphical user interface. Most workstations also have mass storage device such as a disk
drive, but a special type of workstation, called diskless workstation, comes without a disk
drive. Common operating systems for workstations are UNIX and Windows NT. Like
PC, workstations are also single-user computers like PC but are typically linked together
to form a local- area network, although they can also be used as stand-alone systems. In
networking, workstation refers to any computer connected to a local-area network- a
workstation or a personal computer. They are typically found in
10

scientific, industrial and business environments that require high levels of computational
abilities.

3. Minicomputer: It is a midsize multi-processing system capable of supporting up to 250


users simultaneously. They can even capable of handling more I/O devices. They are
also called as mid-range servers. Eg: PDP-11,VAX

4. Mainframe: Mainframe is very large in size and is an expensive computer capable of


supporting hundreds or even thousands of users simultaneously. Mainframe executes
many programs concurrently and supports simultaneous execution of programs (ie) great
processing speeds and very large storage capacity. The chief difference between a
supercomputer and a mainframe is that a supercomputer channels all its power into
executing a few programs as fast as possible, whereas a mainframe uses its power to
execute many programs concurrently. In some ways, mainframes are more powerful than
supercomputers because they support more simultaneous programs. They are designed to
handle huge volumes of data information. They need more sophisticated operating
systems to control and
supervise their operation. Eg: ICL 30, CDC
6600, VAX 8842, IBM438

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

and are employed for specialized applications that require immense


11

amount of mathematical calculations (ie) billions of instructions per second. (number


crunching). Some supercomputers are having computing ability equal to 40,000
minicomputers. For example, weather forecasting, scientific simulations, (animated)
graphics, fluid dynamic calculations, nuclear energy research, electronic design,
seismology, metrology and analysis of geological data (e.g. in petrochemical
prospecting). The best known supercomputer manufacturer is Cray Research.

SOFTWARE
Software refers to a set of computer programs that are required to enable the hardware
to work and perform these operations effectively.

Two tasks of computer software are:


 Control and co-ordinate the hardware components and manage their
performances (System Software)
 Enable the users to accomplish their required tasks (Application Software)

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

 Operating System is the principal component of system software and is


responsible for overall management of computer resources. It also
provides an interface between the computer and the user. The major
functions of OS are process management, memory management, file
management, I/O management, ensuring security of access to computer
resources, commands and instructions’ interpretation and assignment of
utility programs.
 Utility Programs are small programs which provide additional capabilities
to OS-they are not an essential part of OS (ie) OS can execute most of the
programs without having the utility programs. Some of the utility tasks are
search, print, disk defragmenter, system profiler, encryption, virus scanner,
and backup and data recovery.
 Device Driver acts as a translator between I/O devices and the computer.
It interprets the input provided by the user into the computer
understandable form and directs it to the OS. It is a special software that
enables a hardware device to perform an operation according to the
command to the OS.
 System Development Programs are also called as programming software
which allows the users to develop programs in different programming languages.
Eg: Language translators, linkers, debuggers, editors.
 Language translators are compilers, interpreters, assemblers.
 Linkers are used to link the runtime libraries.
 Debuggers are of two types. Machine level debugger debugs the object
code of the program and shows all the lines where bugs are detected.
Symbolic debugger debugs the original source code (HLL).
 Editors are text editor, digital audio editor, graphics editor, binary file
editor, HTML editor, source code editor.

2. APPLICATION SOFTWARE: Application software includes a variety of


programs that are designed to meet the information processing needs of users.
They can be broadly classified into two as:
 Standard Application Programs are also known as general purpose
application programs perform certain common information processing tasks for the
users. These programs significantly increase the productivity of users but also
decreases the time and cost.
Eg:
 Word Processor helps to create, edit, print documents like letters, reports
etc.
 Spreadsheet helps to manipulate and calculate large amounts of tabular
data. It is used as a computational tool by applying formulae on the
value of cells.
13

 DBMS is computer software that helps us to store and maintain records in


a database. Database is a set of records stored in a structured manner
whereas record is a set of similar or dissimilar values related to an entity.
DBMS allows the user to perform various operations such as search,
update, delete on the data stored in the database. The advantages of DBMS
are:
 enables the user to organize all the information in a
strategic manner.
 helps the user to maintain consistency in the information.
 helps to maintain data integrity.
 allows the user to maintain the security of the confidential
information by protecting the database by password.
 accessing information from any system connected in a
network.
Data models available are relational, hierarchical and network. DBMS
includes a query language system which enables a user to perform various
operations.
 DTP (Desk Top Publishing) enables the user to perform various activities
required for publishing a page or a set of pages. Eg: Organizing the
content layout by setting margins and justification properties. There will
be page layout software that enables the user to view changes done at the
time of designing the document. They use ‘WYSIWYG’ (What You See
Is What You Get) technique. The software can manipulate on different
components like text, graphics and images. Eg: Quark Xpress, InDesign,
Microsoft Publisher, Apple Pages.
 Web Browser is software that is used to access the Internet and WWW.
Eg: Internet Explorer from Microsoft, Firefox from Mozilla, Netscape
Navigator from Netscape, Chrome from Google.
IE2.0=1995 by Microsoft using Macintosh OS.
IE3.0=1996 using Windows 95 OS. It has features like Internet Mail,
Windows Address Book, and Windows Media Player.
IE4.0=1997 including Microsoft Outlook Express (E-mail
Software).
IE8.0=A most secured web browser.
 Unique Application Programs or end-user application programs refer to
the development of own programs to accomplish certain tasks that are unique to
end-users’ areas of operations. These programs are usually developed in any high
level language by skilled programmers who have deep knowledge in programming
environment. Eg: Inventory management, pay bills, examination results, ticket
reservation, income tax processing etc.
14
15

UNIT II: Programming Languages: Machine language, Assembly language, High-level


language, 4GL and 5GL-Features of good programming language. Translators:
Interpreters and Compilers. Data: Data types, Input, Processing of data, Arithmetic
Operators, Hierarchy of operations and Output. Different phases in Program
Development Cycle (PDC).
PROGRAMMING LANGUAGES
To write computer programs, we need programming languages as computers don’t
understand natural languages. A programming language is a set of symbols and the rules
governing their use that is utilized in constructing programs.
Why natural languages are not used?
 Natural languages are ambiguous, vaguely structured and have very large and
changing vocabularies.
 In case of natural languages, we can understand even while using poor grammar
and vocabulary, while we cannot expect the system to do like that.
The fundamental types of programming languages are as:

1. MACHINE LANGUAGE is the native language of computers. Computers are


digital devices which have only 2 states-ON (1) and OFF (0). Since a machine
language program consists of a sequence of bits-0’s and 1’s, it is the only language
which the computer can understand directly. The numbers specified and the order in
which they appear, tell the computer what to do. Instruction in machine language
consists of 2 parts:
OPCODE OPERAND
OPCODE (operation code) tells the computer what functions are to be done.
OPERAND tells where to find or store the data.
Advantages:
 Translation free
 High speed
Disadvantages:
-Machine dependent.
-Complex language: It is very difficult for humans to read and write
machine language programs as all instructions have to be converted into binary
code. So the need is hardware expert rather than programmer.
-Error prone: Programmer has to remember all opcodes and hard to keep
track of program logic.
-Tedious: Hard to modify and correct a program and so it is time-
consuming.

2. ASSEMBLY LANGUAGE is a symbolic representation of machine language.


There is usually a one-to-one correspondence between the two (ie) each assembly
language instruction translates into one machine language instruction. It was the
stepping stone for all subsequent language development created by IBM.
Comparatively, people can easily recognize assembly language than machine
language. It uses meaningful abbreviations for machine specific instructions called
16

as mnemonics, which is usually 3 letters long. Whenever an assembly language


program is carried out by a computer, it must be translated into machine language.
This is done by assembler.
17

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

+ Compilers are designed efficiently to point out the errors (easy


debugging).
+ Documentation can be made easily.
But sometimes HLL are less powerful and produce less efficient programs
than their assembly language counterparts.
Eg:
 First HLL was FORTRAN (FORmula TRANslator) used for engineering
and scientific applications in 1950.
 Ada (named after Ada Auguta Byron) was used mostly in US department
of Defence.
 BASIC (Beginner’s All-purpose Symbolic Instruction Code) was a
popular and easy to learn language developed in 1960s.
 C and C++ were developed Dennis Ritchie and Bjarne Stroutstrap
respectively.
 COBOL (COmmon Business Oriented Language) was used to write
program for business applications.
 Java is a very popular modern language especially for networking and
web applications.
 Pascal was a popular language used as a basis of teaching programming
techniques.
 Visual Basic is a version of BASIC that is well-suited for software that
runs on GUIs.

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.

Features of good programming language:


1. Ease of use-easy in writing codes and clarity in syntax, easy to grasp and
readable.
2. Portability-code should be distributed across multiple platforms. PL should be
independent of any particular hardware or OS.
19

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.

Assembler: It translates the assembly language program to machine code.


 Allows the programmer to use mnemonics and symbolic names in writing
source codes.
 Checks the syntax of assembly program and generates error messages or
syntax errors.
11
0

 Translates mnemonics to operation code.


 Translates the register names to system address.
 Assembles all the instruction in the main memory for execution.
 Provides linking facility among the subroutines.
 Generation of output on required output medium.

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.

Eg for input statements:


BASIC-INPUT
C-scanf(), getchar(),getc(),gets()
C++-cin
JAVA-readLine(), nextLine()
Usually it is good practice to have a prompt before entering input as it will help
the user to understand what type of data has to be given as input. There may be other
forms of input like the user may input by clicking or moving the mouse. There will be
another common form of input which does not involve the user at all (ie) data can be
transmitted to a program from a data file stored on disk.
VARIABLE is the quantity that can change value during the execution of
program. So to refer to the data in the subsequent program statements, we will use the
variable name. Al most all the programming languages follow the same rule to form a
variable name (ie) start with alphabet, no use of blank space etc. While naming a variable,
give a meaningful name to the relevant of data, so that all the end-users can understand
easily. A variable has to be declared along with its data type in order to ensure that kind
of data it can hold.

Eg: Addition of two numbers


Start
Read two values in a,b
Compute c->a+b
Display c
Stop
The above sequence is a pseudocode and it is not relevant to any language.
Variables are a,b and c. Input is caught by a and b.

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.

Eg for output statements:


BASIC-PRINT
C-printf(), putchar(),putc(),puts()
C++-cout
JAVA-System.out.println()

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.

PROGRAM DEVELOPMENT CYCLE (PDC)


In developing a computer program to solve a given problem, we follow some
time-honoured problem solving principles. We must
 Completely understand the problem
 Devise a plan to solve it
 Carry out the plan
 Review the results
When this approach is applied to program writing, it entails carrying out the
following tasks.
 Analyze the problem
 Design the program
 Code the program
 Test the program
This process is called a Program Development Cycle. The word Cycle is used here
because we have to often return to previous steps and make modifications before the
process is complete. But in large applications, the cycle is rarely ever complete-these
programs are continually evaluated and modified to meet changing
24

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.

a) Problem Definition: A program is a set of instructions that instructs a computer


how to perform a specific task. It is written in a high level language that can be
implemented on a number of different processors. A collection of programs can be
compared to a recipe book, where each recipe can be assumed as a program. Every recipe
has a list of ingredients (fixed data) and a list of instructions detailing exactly what to do
with those ingredients. When we follow a recipe, we are actually executing a program.
First, the problem is analyzed precisely and completely. Based on understanding, the
developer knows about the scope within which the problem needs to be developed. This
step collects all the facts concerning the problem specifications.
 What is the required output?
 What is the supplied input?
 How will we obtain the required output from the given input?
These questions are directly related to the building blocks of a problem but in reverse
order. If the requirements of the user are not properly understood, then the output is bound
to fall short of the end-user’s expectation. Proper analysis of user requirements are quite
essential for developing the software within time frame, controlled cost and also lead to
faster and accurate development of program. We choose variables to represent the given
input and the required output. We also finalize the formulae to be carried out in the
program.
b) Problem Analysis: After analyzing the problem, the developer needs to develop
various solutions to solve the given problem. From these solutions, the optimum solution
(by experimenting with all the solutions) is chosen, which can solve the problem
comfortably and economically.
25

c) Algorithm Development: After selecting the appropriate solution, algorithm is


developed to depict the basic logic of the selected solution. An algorithm depicts the
solution in logical steps (sequence of instructions). Further, algorithm is represented by
flowcharts and pseudo codes. These tools make program logic clear and they eventually
help in coding.
ALGORITHM FOR SIMPLE INTEREST
Start
Read values for P, N and R
Compute SI=(P*N*R)/100
Display SI
Stop
d) Testing the Algorithm for accuracy: Before converting the algorithms into
actual code, it should be checked for accuracy. The main purpose of checking algorithm is
to identify major logical errors at an early stage, because logical errors are often difficult
to detect and correct at later stages. The testing also ensures that the algorithm is a “true”
one and it should work for both normal as well as unusual data.
e) Coding: After meeting all the design considerations, the actual coding of the
program takes place in the chosen programming language. Depending upon application
domain and available resources, a program can be written by using computer languages of
different levels such as machine, assembly or high-level languages.
f) Test and Debug: Testing actually take place throughout the program
development cycle at each step. For example, in the design phase, we should imagine
that we are the computer and run through the algorithm using simple input data to see if
the output comes or not. This is called as desk-checking. It is common for the initial
program code which contains errors. A program compiler and programmer-designed test
data machine tests the code for syntax errors. The results obtained and compared with
results calculated manually from this test data. Depending upon the complexity of the
program, several rounds of testing may be required.
g) Documentation: Once the program is free from all the errors, it is the duty of
the program developers to ensure that the program is supported by suitable documentation.
These documents should be supplied to the program users. Documenting a program
enables the user to operate the program correctly. It also enables other persons to
understand the program clearly so that it may, if necessary, be modified, or corrected by
someone other than the original programmer.
h) Implementation: After performing all the above-mentioned steps, the program
is installed on the end user’s machine. In this stage, users are also provided with all the
essential documents so that they can understand how the program works. The
implementation can be viewed as the final testing because only after using the program,
the user can point out the drawbacks, if any to the
26

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.

Properties of a good algorithm:


 There must be no ambiguity in any instruction (ie) simple and concise.
 There should not be any uncertainty about which instruction is to be executed next.
 The algorithm should terminate after a finite number of steps (ie) the algorithm
cannot be open-ended.
 The algorithm must be general enough to deal with any contingency (ie) must be
complete and definitely solve the given problem.
 It should use the most efficient logic to solve the given problem within minimum time
(time complexity).
 It should use minimal system memory for its execution (space complexity).
 It should able to generate accurate results for a wide range of data.
27

 It should be easily turned to program of any programming language.


 It is designed with standard conventions so that others are able to easily
modify it while adding additional functionality.

Example: Largest of 2 numbers-Value1 and Value2


Step 1: Start
Step 2: Read two numbers-Value1 and Value2
Step 3: Compare Value1 and Value2. If Value1>=Value2, Max=Value1.
Step 4: If Value2>Value1, Max=Value2.
Step 5: Display the value at MAX as result.
Step 6: Stop.

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.

When to use flowcharts?


1. A flowchart is generally drawn when a new project begins in order to plan for the
project.
2. A flowchart helps to clarify how things are currently working and how they could be
improved. It also assists in finding the key elements of a process, while drawing clear
lines between where one process ends and the next one starts. Developing a flowchart
stimulates communication among participants and establishes a common
understanding about the process. It is recommended that flowcharts be created through
group discussion, as individuals rarely know the entire process and the communication
contributes to improvement. Flowcharts are also very useful to communicate to others
how a process is performed and enables understanding of the logic of a process.
Flowcharts are used to help team members, to identify who provides inputs or
resources to whom, to establish important areas for monitoring or data collection, to
identify areas for improvement or increased efficiency, and to generate hypotheses
about causes.
3. Flowcharts also used to uncover steps that are redundant, unreachable or misplaced.
4. Flowcharts are very useful for documenting a process (simple or complex) as it eases
the understanding of the process.

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

 Can be done easily on a word processor.


Disadvantages of Pseudocode:
 It’s not visual.
 There is no accepted standard, so it varies widely from user to user.
Eg-Computing average marks for a class:
SET total to zero
SET counter to one
WHILE counter is less than or equal to ten
INPUT the student’s grade
ADD the grade to the total End
While
SET average as total divided by ten
PRINT average.

CODING, DOCUMENTING AND TESTING A PROGRAM


Once a suitable program has been created to solve a given problem, it is time to
code the program (ie) translation of pseudocode of the design into corresponding
statements in a particular programming language. The result of the program can be seen in
the computer. Here the developers should be familiar with the programming language
like C, C++ or Java to write correct program.
The notion of documenting a program means providing explanatory material about
the program for other programmers and users. Annotating each part of program is
necessary, (ie) documentation is a program with comments. A comment is text inserted
into the program for explanatory purpose, but ignored by the computer while executing.
How they are ignored means a certain character or a combination of characters indicates a
particular statement in a program as comment line.
Eg:
BASIC ‘ (apostrophe) or REM
PASCAL Text enclosed between * and *
JAVA/C/C++ /* .... */ or //
VB ‘ (apostrophe)

Comments are of two types as:


1. Header comments: Appear at the beginning of a program that provides
general information about the program.
2. Step comments: Appear throughout the program to explain the purpose of
specific portions of code.

Certain commercial program includes another form of documentation to help


customers learn to use the software available as user’s guide or on-screen help called as
external documentation. It is necessary to test a program at every phase of the program
development cycle to ensure that it is error-free. The final and most important, testing
takes places when the code has been completed-we run the
31
3

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

MODULAR PROGRAMMING: A good way to begin the job of designing is to identify


major tasks which can be divided into subtasks. The individual fundamental sub tasks are
called modules. The process of breaking down a problem into simpler sub problems is
called as Top-Down Design; splitting a program into module is called Modular
Programming.

Features of a module are:


 A module is relatively short.
 A module is assigned with a task.
 A module is self-contained and independent of other modules (high cohesion and
low coupling)

There will a number of modules in a complex program. To execute every module,


there will be one parent module/calling module. Once a module is called, the control
goes to that called module and returns to the calling module. Usually every program has a
special module called as main module (ie) where every program execution begins. It is
not a sub module of anyone.

Benefits of modular programming are:


1. Program readability increases and reduces the time to locate the errors.
2. Programmer productivity is increased and hence easier to design code and test
the program.
3. A singe module can be used in more than one place and reduces the amount of
code.
4. Different modules can be programmed by different set of programmers at the same
time.

Hierarchy Chart or Structure Chart is a solution approach that suggests a top-


down solution of a problem. Since it is difficult to comprehend the solution for a large
problem, we can decompose into smaller tasks-find the solution for the smaller tasks and
combine all the solution to form the large problem. It does not provide any details about
program logic.
31
5

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:

RELATIONAL OPERATORS: A relational operator is a programming language


construct or symbols that test or defines some kind of relation between two entities.
There are six basic relational operators which will produce Boolean value as answer
(true/false). All the operators can be applied to both numeric and character-based data.

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.

Not equal to != (or) <>


Greater than or equal to >=
Lesser than or equal to <=
Eg:
3 < 4 true
5<= 9 true
4 == 7 false
8.3 != 2.1 true
31
6

‘h’!=’B’ true

LOGICAL OPERATORS: The concept of logical operators is simple. They allow a


program to make a decision based on multiple conditions. Each operand is considered a
condition that can be evaluated to a true or false value. Then the value of the conditions
is used to determine the overall value of the op1 operator op2 or
!op1 grouping. They also produce boolean value (true/false) as answer.

AND Produce true if all conditions are true else false


OR Produce true if any one of the conditions is true else false
NOT or ! Negate the condition to opposite value

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.

1. IF THEN: The simplest type of selection structure is the If..then or single


alternative structure.
31
7

Syntax: Flowchart:

If (test expression) then


Body of if
End if

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;

2. IF..THEN..ELSE: If-then-else or dual alternative structure has the following


general form:
31
8

Syntax: Flowchart:

If (test expression) then


Body of if
Else
Body of else
End if

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;

3. ELSE IF LADDER (several alternative using if): We can construct a multiple


alternative structure using several applications of If-then or If-then-else structure. Here
more conditions upon certain parameters will be checked and all those conditions are
grouped together.

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

If (score=6 or score=7) then


Set rating=”C”
End if
If (score>=1 or score<=5) then
Set rating=”D”
End if
40

Solution-2: Sequence of if-then-else statements


If (score=10) then
Set rating=”A”
else If (score=8) or (score=9) then
Set rating=”B”
else If (score=6) or (score=7) then
Set rating=”C”
else
Set rating=”D”
End if;
41

4. SEVERAL ALTERNATIVES USING CASE STRUCTURE: To make the


multiple alternatives more effective, many programming languages contain a statement
called case or switch. This statement contains a single test expression, which should gives
the result as integer or character determines the block of the code to be executed.
The test expression will be evaluated first. The result will be compared against the
list of values. Which value is perfectly matched, the corresponding block of statements
will be executed. If no match is found, the block of statements enclosed under keyword
“default” will be executed.

Syntax: Flowchart:

switch (test expression)


case option1:..............
case option2:..............
case option3:..............

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.

APPLICATIONS OF SELECTION STRUCTURES: Two important applications of


selection structures are:
1. Defensive Programming: It involves the inclusion of statements within a program
to check, during execution for improper data. The program segment that catches
and reports an error of this sort is called as error trap.
Eg-1: Avoiding a potential division by zero Write
“Enter a number to find its reciprocal” Input
num
If num<>0 then
Set ans=1/num
Write “Reciprocal=”,ans
43

Else
Write “Don’t enter zero please”
End if

Eg-2: Dealing with square-root: Most programming languages have built-in


function that compute square root of a number as sqrt(number) where the argument
many be a number, variable or expression whose value should be non-negative.
Write “Enter a number to find square root”
Input num
If num>=0 then
Write “Square root=”,sqrt(num)
Else
Write “Enter a positive number”
End if

2. Menu-Driven Programs: To make the programs more user-friendly, we can go for


menu programs. Menu screen will displays a list of choices (program’s major
functions) and the user has to select one choice at a time. The concept of menu
enhances user-friendliness. Programs that present their options in this fashion,
instead of by requiring their users to memorize commands, are said to be menu-
driven. Selection of a choice will lead to another detailed submenu or directly into
the specified task.
Eg-1:
If (opt=1) then
call function1
Else If (opt=2) then
call function2
Else If (opt=3) then
call function3
.........
Eg-2:
select (opt)
case 1: call function1
case 2: call function2
case 3: call function3
..........
End case
Examples:
1. If amt>0 then [amt=5,-1]
Write amt
End if
Write amt
44

2. If amt>0 then [amt=5,-1]


Write amt
Else
Set amt=-amt
Write amt
End if

3. Write “Enter CP and SP”


Input CP,SP
Set amt=SP-CP
If amt>0 then
Write “Profit=”,amt
Else
Set amt=-amt Write
“Loss=”,amt
End if
45

Write “Calculation completed”

4. Construct a multiple-alternative structure that displays “low” if x is equal to 0,


“medium”, if x is equal to 1 or 2, or “high”, if x is greater than 2 but less than or
equal to 10. Use a set of if-then, if-then-else and case statement.

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.

Pre-test Loop /Entry-controlled Loop Post-test Loop/Exit-controlled Loop


Exit condition occurs before the body of Exit condition occurs after the body of the
the loop. loop.
Condition will be evaluated first. Body of the loop will be executed first.
If the condition is false at the first time Even though the condition is false at the
itself, the body of the loop will not be first time itself, the body of the loop will
executed at least once. be executed at least once.
The variables appearing in the exit
The variables appearing in the exit
condition may be initialized in the body
condition must be initialized.
of the loop.

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

3. Counter-Controlled Loops: A counter controlled loop is one that is executed a


fixed number, N, where N is known prior to entering the loop for the first time. Counter
(N) will keep the number of passes through the loop. When the counter reaches the
preset number, the loop is exited. For loop comes under the category of built-in
counter controlled loop. We can also construct while or repeat-until loop as counter
controlled loop.

Syntax: Flowchart:

for counter=initial value step increment


to limit value
body of the loop
end for

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-1: Print square of numbers from 1 to n


Prompt for and input the value for n Initialize
the variable count to 1
While count<=n
Write count,count^2
Add 1 to count
End while

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

write “Inside loop”


end for
write “After loop”
Eg-4:
set n=1
for k=n step 1 to n*3
write n,k
end for

Eg-5: Print numbers 10,20,30...100

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:

Eg-1: Nested for loop


for i=1 step 1 to 5 //condition1
write “Outer loop iteration”, i
for j=1 step 1 to 2 //condition2
write”i=”,i;”j=”,j
end for
end for
41
0

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

Other kinds of nesting of for loop are: 1.


for i=....
for j=....
end for(j)
for k=......
end for(k)
end for(i)

for i=....
for j=....
for k=....
end for(k)
end for(j)
end for(i)

Eg-2: Nesting other kinds loop


Initialize sum to 0 (ie) set sum=0
Repeat
Prompt for and Input a number as num
While num<>0 (use 0 as a sentinel value)
Set sum=sum+num
Prompt for and input a number as num
End while
Write sum
Prompt user for another set of numbers and input response (y/n) Until
response<>”n”
50

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.

APPLICATIONS OF REPETITION STRUCTURES:


1. Using sentinel-controlled loops to input data: Loops are often used to input large
amounts of data: one data is entered at a time. The exit condition must cause the
loop to be exited after all data have been input. Usually it is a best way to make the
user to enter special item called sentinel value (signal to end the input). It acts as
end-of-data marker else the program will be caught in infinite loop. For example,
 For a list of positive numbers as input, -1 can act as sentinel.
 For a list of non-zero numbers as input, 0 can act as sentinel.
Eg:
Write “Enter the number of hours worked. Enter -1 to exit”
Input hours
While hours<>-1
Write “Enter the rate of pay”
Input rate
Set salary=hours*rate
51

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.

Eg: Finding sum


Initialize the sum to 0
Prompt for and input number as num
While num>0
Add num to sum
Prompt for and input next number as num
End while
Write sum
52

Eg: Finding average


Initialize count to 0
Initialize sum to 0
Prompt for and input number as num
While num>0
Add count by 1
Add num to sum
Prompt for and input next number as num
End while
Prompt for and write sum
Set avg=sum/count Prompt
for and write avg

inprotected.com

You might also like