0% found this document useful (0 votes)
1 views

GE3151- PROBLEM SOLVING AND PYTHON PROGRAMMING- UNIT-I NOTES

The document provides an overview of computational thinking and problem solving, focusing on the fundamentals of computing, including the definition of computers, their generations, and various components such as the CPU, memory, and language processors. It details the evolution of computers from vacuum tubes to artificial intelligence, highlighting key characteristics and examples of each generation. Additionally, it discusses different types of computers, programming languages, and the importance of software in computing systems.

Uploaded by

Sanjay t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

GE3151- PROBLEM SOLVING AND PYTHON PROGRAMMING- UNIT-I NOTES

The document provides an overview of computational thinking and problem solving, focusing on the fundamentals of computing, including the definition of computers, their generations, and various components such as the CPU, memory, and language processors. It details the evolution of computers from vacuum tubes to artificial intelligence, highlighting key characteristics and examples of each generation. Additionally, it discusses different types of computers, programming languages, and the importance of software in computing systems.

Uploaded by

Sanjay t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

UNIT – I COMPUTATIONAL THINKING AND PROBLEM SOLVING

Fundamentals of Computing – Identification of Computational Problems - Algorithms, building


blocks of algorithms – Statements, State, Control flow, Functions – Notations – Pseudo code,
flowchart, programming language, Algorithmic problem solving, simple strategies for developing
algorithms – iteration, recursion. Illustrative problems: find minimum in a list, insert a card in a
list of sorted cards, guess an integer number in a range. Tower of Hanoi.
1. FUNDAMENTALS OF COMPUTING
1. Draw the block diagram of central processing unit. (2 MARKS) (DEC 2015)
2. Explain different types of computer generations with processing speed and its
characteristics. (8 MARKS) (JAN 2018)
3. Explain characteristics and capabilities of computer system.(8 MARKS) (JAN 2018)
4. Differentiate between Assembler, Interpreter and compiler with an example.
(8 MARKS) (MAR 2018)
5. Define Debugging. (2 MARKS) (JAN2021)
6. Discuss various data storage and retrieval techniques. (8 MARKS) (JAN 2021)

COMPUTER:

A computer is an electronic device that uses raw information as data and processes it
accordingly to give the required result. The main function of the computer is to store, retrieve,
and process data. Now a day’s its uses have been extended to type documents, play online
games, web browsing, editing & creating spreadsheets, office presentations, PowerPoint
meetings & video consoles, etc..

Input Process Output

Memory

A complete computer system consists of four parts

• Hardware: Hardware represents the physical and tangible components of the


computer.
• Software: Software is a set of electronic instructions consisting of complex codes
(Programs)that make the computer perform tasks.
• User: The computer operators are known as users.
• Data: Consists of raw facts, which the computer stores and reads in the form of
numbers.
GENERATIONS OF COMPUTER:

1)First Generation Computers: Vacuum Tubes (1940-1956)

The technology behind the primary generation computers was a fragile glass
device, which was called vacuum tubes. These computers were very heavy and really large in
size. These weren’t very reliable and programming on them was a really tedious task as they
used high-level programming language and used no OS. First-generation computers were used
for calculation, storage, and control purpose. They were too bulky and large that they needed a
full room and consume rot of electricity.

First generation computers are,

• ENIAC: Electronic Numerical Integrator and Computer, built by J. Presper Eckert and
John V. Mauchly was a general-purpose computer. It had been very heavy, large, and
contained 18,000 vacuum tubes.
• EDVAC: Electronic Discrete Variable Automatic Computer was designed by von
Neumann. It could store data also as instruction and thus the speed was enhanced.
• UNIVAC: Universal Automatic Computer was developed in 1952 by Eckert and Mauchly.

Main characteristics of first generation computers are,

Main electronic component Vacuum tube.

Programming language Machine language.

Main memory Magnetic tapes and magnetic drums.

Input/output devices Paper tape and punched cards.

Speed and size Very slow and very large in size (often taking up entire room).

Examples of the first generation IBM 650, IBM 701, ENIAC, UNIVAC1, etc.

2) Second Generation Computers: Transistors (1956-1963)

Second-generation computers used the technology of transistors rather than bulky


vacuum tubes. Another feature was the core storage. A transistor may be a device composed of
semiconductor material that amplifies a sign or opens or closes a circuit.

Transistors were invented in Bell Labs. The use of transistors made it possible to
perform powerfully and with due speed. It reduced the dimensions and price and thankfully
the warmth too, which was generated by vacuum tubes. Central Processing Unit (CPU),
memory, programming language and input, and output units also came into the force within
the second generation.
Programming language was shifted from high level to programming language and
made programming comparatively a simple task for programmers. Languages used for
programming during this era were FORTRAN (1956), ALGOL (1958), and COBOL (1959).

Main characteristics of second generation computers are,

Main electronic component Transistor.

Programming language Machine language and assembly language.

Memory Magnetic core and magnetic tape/disk.

Input/output devices Magnetic tape and punched cards.

Power and size Smaller in size, low power consumption, and generated less.

Examples of second PDP-8, IBM1400 series, IBM 7090 and 7094, UNIVAC 1107, CDC
generation 3600 etc.

3) Third Generation Computers: Integrated Circuits. (1964-1971)

During the third generation, technology envisaged a shift from huge transistors to
integrated circuits, also referred to as IC. Here a variety of transistors were placed on silicon
chips, called semiconductors. The most feature of this era’s computer was the speed and
reliability. IC was made from silicon and also called silicon chips.

A single IC, has many transistors, registers, and capacitors built on one thin slice of
silicon. The value size was reduced and memory space and dealing efficiency were increased
during this generation. Programming was now wiped out Higher level languages like BASIC
(Beginners All-purpose Symbolic Instruction Code). Minicomputers find their shape during
this era.

Main characteristics of third generation computers are,

Main electronic component Integrated circuits (ICs)

Programming language High-level language

Memory Large magnetic core, magnetic tape/disk

Input / output devices Magnetic tape, monitor, keyboard, printer, etc.

Examples of third generation IBM 360, IBM 370, PDP-11, NCR 395, B6500, UNIVAC 1108, etc.
4) Fourth Generation Computers: Micro-processors (1971-Present)

In 1971 First microprocessors were used, the large scale of integration LSI circuits
built on one chip called microprocessors. The most advantage of this technology is that one
microprocessor can contain all the circuits required to perform arithmetic, logic, and control
functions on one chip.

The computers using microchips were called microcomputers. This generation


provided the even smaller size of computers, with larger capacities. That’s not enough, then
Very Large Scale Integrated (VLSI) circuits replaced LSI circuits. The Intel 4004chip, developed
in 1971, located all the components of the pc from the central processing unit and memory to
input/ output controls on one chip and allowed the dimensions to reduce drastically.

Technologies like multiprocessing, multiprogramming, time-sharing, operating


speed, and virtual memory made it a more user-friendly and customary device. The concept of
private computers and computer networks came into being within the fourth generation.

Main characteristics of fourth generation computers are,

Main electronic Very large-scale integration (VLSI) and the microprocessor (VLSI has
component thousands of transistors on a single microchip).

Memory semiconductor memory (such as RAM, ROM, etc.)

Input/output devices pointing devices, optical scanning, keyboard, monitor, printer, etc.

Examples of fourth
generation IBM PC, STAR 1000, APPLE II, Apple Macintosh, Alter 8800, etc.

5) Fifth Generation Computers:

The technology behind the fifth generation of computers is AI. It allows computers to
behave like humans. It is often seen in programs like voice recognition, area of medicines, and
entertainment. Within the field of games playing also it’s shown remarkable performance
where computers are capable of beating human competitors.

The speed is highest, size is that the smallest and area of use has remarkably
increased within the fifth generation computers. Though not a hundred percent AI has been
achieved to date but keeping in sight the present developments, it is often said that this dream
also will become a reality very soon.

In order to summarize the features of varied generations of computers, it is often


said that a big improvement has been seen as far because the speed and accuracy of
functioning care, but if we mention the dimensions, it’s being small over the years. The value is
additionally diminishing and reliability is in fact increasing.
Main characteristics of fifth generation computers are,

Based on artificial intelligence, uses the Ultra Large-Scale Integration (ULSI)


Main technology and parallel processing method (ULSI has millions of transistors on
electronic a single microchip and Parallel processing method use two or more
component microprocessors to run tasks simultaneously).

Language Understand natural language (human language).

Size Portable and small in size.

Input / output Trackpad (or touchpad), touchscreen, pen, speech input (recognize
device voice/speech), light scanner, printer, keyboard, monitor, mouse, etc.

Example Desktops, laptops, tablets, smartphones, etc.

Characteristics:

• Speed, Accuracy
• Storage and Retrieval
• Repeated Processing Capabilities
• Reliability, Flexibility, Low cost

DATA PROCESSING UNITS:

Central Processing Unit (CPU) consists of the following features

• CPU is considered as the brain of the computer.


• CPU performs all types of data processing operations.
• It stores data, intermediate results, and instructions (program).
• It controls the operation of all parts of the computer.

CPU itself has following three components.

• Memory or Storage Unit


• Control Unit
• ALU(Arithmetic Logic Unit)

Memory or Storage Unit

• This unit can store instructions, data, and intermediate results. This unit supplies
information to other units of the computer when needed. It is also known as internal
storage unit or the main memory or the primary storage or Random Access Memory
(RAM).
• Its size affects speed, power, and capability. Primary memory and secondary memory are
two types of memories in the computer. Functions of the memory unit are −
• It stores all the data and the instructions required for processing.
• It stores intermediate results of processing.
• It stores the final results of processing before these results are released to an output
device.
• All inputs and outputs are transmitted through the main memory.

Control Unit

This unit controls the operations of all parts of the computer but does not carry out any
actual data processing operations.

Functions of this unit


• It is responsible for controlling the transfer of data and instructions among other units of
a computer.
• It manages and coordinates all the units of the computer.
• It obtains the instructions from the memory, interprets them, and directs the operation of
the computer.
• It communicates with Input/Output devices for transfer of data or results from storage.
• It does not process or store data.

ALU (Arithmetic Logic Unit)

This unit consists of two subsections namely,


• Arithmetic Section
• Logic Section

Arithmetic Section-Function of arithmetic section is to perform arithmetic operations like


addition, subtraction, multiplication, and division. All complex operations are done by making
repetitive use of the above operations.

Logic Section-Function of logic section is to perform logic operations such as comparing,


selecting, matching, and merging of data.

The Input Unit


Computer Input unit means the device of the input and a part of the computer hardware
which is used for the transport of the data processing system involves the information devices of
the computer with the control and data signals of the computer.
Example – Mouse, Camera, and Keyboard

The Output Unit


Computer Output is the device which deals with transmitting the data of the computer
among the device and the clients. The computer is designed for humans in the form of audio and
video format.
Example – Monitors, printers, microphones, and headphones.

The Processing Unit


The Processing Unit is the hardware device of the computer that deals with the
instruction of the computer program and is known as the CPU (central processing unit). It deals
with the basic logical information of the computer and arithmetical and the Input or Output
device functions.
Fig: The relationship between different hardware components

Language Processors:

Assembler: This language processor converts the program written in assembly language into
machine language.
Interpreter: This language processor converts High-Level Language program into machine
language by converting and executing it line by line.
Compiler: It also converts the HLL program into machine language but the conversion manneris
different. It converts the entire HLL program in one go and reports all the errors of the program
along with the line numbers.
Software: Software represents the set of programs that govern the operation of a computer
system and make the hardware run. This type of software is tailor-made software according to a
user’s requirements.

System Software Application Software

System Software maintain the system resources Application software is built for specific
and gives the path for application software to run. tasks.

Low level languages are used to write the system While high level languages are used to
software. write the application software.

While its a specific purpose software.


It is a general-purpose software and simple. Complex compared to system software.

While without application software


Without system software, the system can’t run. system always runs.

System software runs when the system is turned While application software runs as per
on and stop when the system is turned off. the user’s request.

Example: Application software are


Example:OS Photoshop, VLC player etc.
DIFFERENT TYPES OF COMPUTERS:

Analog computers

1. Analog computers always take input in form of signals.


2. The input data is not a number infect a physical quantity like temp., pressure, speed,
velocity.
3. Signals are continuous of (0 to 10 V).
4. Accuracy 1% Approximately.
Example: Speedometer.

Digital Computers

1. These computers take the input in the form of digits & alphabets & converted it into
binary format.
2. Digital computers are high speed, programmable electronic devices.
3. Signals are two level of (0 for low/off 1 for high/on).
4. Accuracy unlimited.
Examples: Computer used for the purpose of business and education is also an example of
digital computers.

Hybrid Computer

1. The combination of features of an analog and digital computer is called a Hybrid


computer.
2. The main examples are central national defence and passenger flight radar system.
3. They are also used to control robots.

Super Computer

1. Most Expensive. The biggest in size.


2. It can process trillions of instructions in seconds.
3. This computer is not used as a PC in a home neither by a student in a college.
4. Used by Govt. for different calculations and heavy jobs.
5. Supercomputers are used for the heavy stuff like weather maps, construction of atom
bombs,earthquake prediction etc.

Mainframes

1. It can also process millions of instruction per second.


2. It can handle processing of many users at a time.
3. Less expensive than Supercomputer, It can cost up to thousands of Dollars.
4. It is commonly used in Hospitals, Air Reservation Companies as it can retrieve data on a
hugebasis.
5. This is normally too expensive and out of reach from a salary-based person.

Mini Computer

1. These computers are preferred mostly by small type of business personals, colleges etc.
2. These computers are cheaper than above two.
3. It’s an intermediary between microcomputer and mainframe.
Micro Computer/ Personal Computer

1. It is mostly preferred by Home Users.


2. Cost is less compared to above.
3. Small in size.
4. A microcomputer contains a central processing unit on a microchip in the form of read-
only memory and random-access memory, and a housed in a unit that is usually called a
motherboard.

Notebook Computers

1. Notebook computers typically weigh less than 6 pounds and are small enough to fit easily
in abriefcase.
2. The principal difference between a notebook computer and a personal computer is the
displayscreen.
3. Many notebook display screens are limited to VGA resolution.

PROGRAMMING LANGUAGES:

There are two major types of programming languages. Low-Level Languages and High-Level
Languages. Low-Level languages are further divided into Machine language and Assembly
language.

• Low-Level Languages: The term low level means closeness to the way in which the
machine has been built. Low-level languages are machine oriented and require
extensive knowledge of computer hardwareand its configuration.

• Machine Language: Machine Language is the only language that is directly understood by
the computer. It does not need any translator program. We also call it machine code and
it is written as strings of 1's (one) and 0’s (zero). When this sequence of codes is fed to
the computer, it recognizes the codes and converts it into electrical signals needed to run
it.

For example, a program instruction may look like this: 1011000111101


It is not an easy language for you to learn because of its difficult to understand. It is efficient for
the computer but very inefficient for programmers. It is considered to the first-generation
language.

Advantage:

• Program of machine language run very fast because no translation program is required
for the CPU.

Disadvantages:

• It is very difficult to program in machine language. The programmer has to know details
of hardware to write a program.
• The programmer has to remember a lot of codes to write a program which results in
programerrors.
• It is difficult to debug the program.
Assembly Language:

• It is the first step to improve the programming structure. You should know that
computer can handle numbers and letter. Therefore, some combination of letters can be
used to substitute for anumber of machine codes.
• The set of symbols and letters forms the Assembly Language and a translator program is
required to translate the Assembly Language to machine language.
• This translator program is called `Assembler'. It is considered to be a second-generation
language.

Advantages:

• The symbolic programming of Assembly Language is easier to understand and saves a lot
oftime and effort of the programmer.
• It is easier to correct errors and modify program instructions.
• Assembly Language has the same efficiency of execution as the machine level language.
Because this is a one-to-one translator between assembly language program and its
corresponding machine language program.

Disadvantages:

• Assembly language is machine dependent.


• A program written for one computer might not run-on other computers with different
hardware configuration.

High-Level languages:

• You know that assembly language and machine level language require deep
knowledge of computer hardware whereas in a higher language you have to know
only the instructions in English words and logic of the problem irrespective of the type
of computer you are using.
• Higher level languages are simple languages that use English and mathematical
symbols like +,-, %, / for its program construction.
• You should know that any higher-level language has to be converted to machine
language forthe computer to understand.
• Higher level languages are problem-oriented languages because the instructions are
suitablefor solving a particular problem.
• For example, COBOL (Common Business Oriented Language) is most suitable for a
business-oriented language where there are very little processing and huge output.
• There are mathematically oriented languages like FORTRAN (Formula Translation)
and BASIC (Beginners All-purpose Symbolic Instruction Code) where very large
processing isrequired. Thus, a problem-oriented language designed in such a way that
its instruction may be written more like the language of the problem. Example,
businessmen use the business term and scientists use scientific terms in their
respective languages.

Advantages of High-Level Languages:

• Higher level languages have a major advantage over machine and assembly languages
thathigher level languages are easy to learn and use.
• It is because that they are similar to the languages used by us in our day-to-day life.
COMPUTER HARDWARE:

Computer hardware comprises the physical part of a computer system. It includes the all-
important components of the central processing unit (CPU) and main memory. It also includes
peripheral components such as a keyboard, monitor, mouse, and printer.

Fundamental Hardware Components

• The central processing unit (CPU) is the “brain” of a computer system, containing
digital logiccircuitry able to interpret and execute instructions.
• Memory is where currently executing programs reside, which the CPU can directly and
very quickly access. Main memory is volatile; that is, the contents are lost when the
power is turned off. In contrast, secondary memory is nonvolatile, and therefore
provides long-term storage of programs anddata.
1. Primary / Main memory: Primary memory is the computer memory that is directly
accessible by CPU. It is comprised of DRAM and provides the actual working space to the
processor. It holds the data and instructions that the processor is currently working on.
2. Secondary Memory / Mass Storage: The contents of the secondary memory first get
transferred to the primary memory and then are accessed by the processor, this is
because the processor does not directly interact with the secondary memory.

Primary memory Secondary memory

Primary memory is temporary. Secondary memory is permanent.

Primary memory is directly accessible by Secondary memory is not directly accessible


Processor/CPU. by the CPU.

Secondary memory devices are less


Primary memory devices are more expensive expensive when compared to primary
than secondary storage devices. memory devices.

The memory devices used for primary The secondary memory devices are magnetic
memory are semiconductor memories. and optical memories.

Primary memory is also known as Main Secondary memory is also known as External
memory or Internal memory. memory or Auxiliary memory.

Examples: RAM, ROM, Cache memory, PROM, Examples: Hard Disk, Floppy Disk, Magnetic
EPROM, Registers, etc. Tapes, etc.

• Input/output devices include anything that allows for input (such as the mouse and
keyboard) or output (such as a monitor or printer).
• Finally, buses transfer data between components within a computer system, such as
between theCPU and main memory.
Devices:

1. Storage Devices: Hard Drive, CD Drive, USB Stick, DVD Drive, SD Card
2. Input Devices: Keyboard, Mouse, Scanner, OCR Reader, Webcam, Touch Screen,
Microphone
3. Processing Devices: CPU, GPU
4. Output Devices: Printer, Monitor, Projector, Speakers, Headphones, Tv Screen
5. Communication Devices: Modem, Wifi card, Network card, Bluetooth

OPERATING SYSTEMS:

• An operating system is software that has the job of managing and interacting with the
hardware resources of a computer.
• It is intrinsic to the operation a computer; it is referred to as system software.
• It acts as the “middle man” between the hardware and executing application programs
• It also provides a particular user interface.
• It determines the “look and feel” of the user interface and how the user interacts with the
system,and not the particular model computer.

Syntax, Semantics, and Program Translation

The syntax of a language is a set of characters and the acceptable arrangements (sequences) of
those characters.
The semantics of a language is the meaning associated with each syntactically correct sequence
of characters.
Program Translation - A central processing unit (CPU) is designed to interpret and execute a
specific set of instructions represented in binary form (i.e., 1s and 0s) called machine code.

A compiler is a translator program that translates programs directly into machine code to
beexecuted by the CPU.
An interpreter executes program instructions in place of (“running on top of”) the CPU.
Program Debugging: Syntax Errors Vs. Semantic Errors
Program debugging is the process of finding and correcting errors (“ bugs”) in a
computerprogram.

Syntax errors:
They are caused by invalid syntax (for example, entering prnt instead of print). Since a
translator cannot understand instructions containing syntax errors, translators terminate
whenencountering such errors indicating where in the program the problem occurred.

Semantic errors
Generally called logic errors are errors in program logic. Such errors cannot be
automatically detected, since translators cannot understand the intent of a givencomputation.

For example, if a program computed the average of three numbers as follows,


(num1 + num2 + num3) / 2.0
a translator would have no means of determining that the divisor should be 3 and not 2.
Computers do not understand what a program is meant to do, they only follow the
instructions.

BINARY NUMBER SYSTEM:


• A binary number system is one of the four types of number system. In computer
applications, where binary numbers are represented by only two symbols or digits, i.e. 0
(zero) and 1(one). The binary numbers here are expressed in the base-2 numeral system.
For example, (101)2 is a binary number. Each digit in this system is said to be a bit. Learn
about the number system here.
• Number System is a way to represent numbers in computer architecture.
• There are four different types of the number system, such as:
1. Binary number system (base 2)
2. Octal number system (base 8)
3. Decimal number system(base 10)
4. Hexadecimal number system (base 16).

Example: Convert 4 in binary.


Solution:
4 in binary is (100)2.
Here, 4 is represented in the decimal number system, where we can represent the number using
the digits from 0-9. However, in a binary number system, we use only two digits, such as 0 and 1.
Now, let’s discuss how to convert 4 in binary number system.
The following steps help to convert 4 in binary.
Step 1: First, divide the number 4 by 2. Use the integer quotient obtained in this step as the
dividend for the next step. Continue this step, until the quotient becomes 0.

Dividend Remainder

4/2 = 2 0

2/2 = 1 0

1/2 = 0 1

Step 2: Now, write the remainder in reverse chronological order. (i.e from bottom to top).
Here, the Least Significant Bit (LSB) is 0 and the Most Significant Bit (MSB) is 1.
Hence, the decimal number 4 in binary is 1002
So, if we want to find how many bits does 4 in binary have? we have to count the number of
zeros and ones.
So, 4 in binary is 1002. Here, there are 2 zeroes and 1 one. Hence, we have 3 bits.
Therefore, the number of bits does 4 in binary have is 3.

2. IDENTIFICATION OF COMPUTATIONAL PROBLEMS

1. List the steps of identification of Problem. (2MARKS)(NOV 2018)


2. Define Program Implementation. (2MARKS)(MAR 2019)

TO SOLVE A PROBLEM

Representation

Captures all the relevant aspects of the problem. A representation that leaves out details of
whatis being represented is a form of abstraction.

Example1: Man, Cabbage, Goat, Wolf (Brute force approach)

• A farmer went to a market and purchased a wolf, a goat, and a cabbage. On his way home,
the farmer came to the bank of a river and rented a boat. But crossing the river by boat, the
farmer could carry only himself and a single one of his purchases: the wolf, the goat, or the
cabbage.
• If left unattended together, the wolf would eat the goat, or the goat would eat the
cabbage.
• The farmer's challenge was to carry himself and his purchases to the far bank of the river,
leaving each purchase intact.

The first step that must be taken is to let the goat go across the river, as any other actions will
result in the goat or the cabbage being eaten. When the farmer returns to the original side, he
has the choice of taking either the wolf or the cabbage across next. If he takes the wolf across, he
would have to return to get the cabbage, resulting in the wolf eating the goat. If he takes the
cabbage across second, he will need to return to get the wolf, resulting in the cabbage being
eaten by the goat. The dilemma is solved by taking the wolf (or the cabbage) over and bringing
the goat back. Now he can take the cabbage (or the wolf) over, and finally return to fetch the
goat.

His actions in the solution are summarized in the following steps:


• Take the goat over
• Return to other side
• Take the wolf or cabbage over
• Return with the goat
• Take the cabbage or wolf over
• Return
• Take goat over
• Thus there are seven crossings, four forward and three back.

LIMITS OF COMPUTATIONAL PROBLEM SOLVING:

Once an algorithm for solving a given problem is developed or found, an important


question is, “Can asolution to the problem be found in a reasonable amount of time?” If not, then
the particular algorithm is limited practical use.

EXAMPLE 1: The Traveling Salesman problem (Using Brute force method)


It is a classic computational problem in computer science. The problem is to find the
shortest route of travel for a salesman needing to visit a given set of cities. In a brute force
approach, the lengths of all possible routes would be calculated and compared to find the
shortest one.
There are various ways to solve this problem. The travelling salesman problem is
a permutation problem. There can be n! total ways to solve permutation problems. In this
approach, we’ll generate all the possible permutations (routes).

The algorithm is as follows:


Step 1: Choose a city to act as a starting point (let’s say city1).
Step 2: Find all possible routes using permutations. For n cities, it will be (n-1)!.
Step 3: Calculate the cost of each route and return the one with the minimum cost.
THE PROCESS OF COMPUTATIONAL PROBLEM SOLVING:

• Computational problem solving does not simply involve the act of computer
programming.
• It is a process, with programming being only one of the steps.
• Before a program is written, a design for the program must be developed.
• Before a design can be developed, the problem to be solved must be well understood.
• Once written, the program must be thoroughly tested.
Step 1: Problem Analysis-Understanding the Problem

• Once a problem is clearly understood, the fundamental computational issues for solving it
can bedetermined.
• For the Man, Cabbage, Goat, Wolf (MCGW) problem, a brute-force algorithmic
approach of trying all possible solutions .Small number of steps for reaching a solution.
• (example)For both the Traveling Salesman problem and the game of chess, the brute-
force approach is infeasible.

Knowing What Constitutes a Solution

For some problems, there is only one solution. For others, there may be a number (or infinite
number) of solutions. Program may be stated as finding,
• A solution
• An approximate solution
• A best solution
• All solutions
For the MCGW problem, there are an infinite number of solutions.
Finally, for the game of chess, the goal (solution) is to win the game.
In the Traveling Salesman problem there is only one solution.

Step 2: Program Design

Describing the Data Needed


For the Man, Cabbage, Goat, Wolf problem, a list can be used to represent the correct location
(east and west) of the man, cabbage, goat, and wolf.

For the Calendar Month problem, the data include the month and year, the number of days in
each month, and the names of the days of the week.

For the Traveling Salesman problem, the distance between each pair of cities must be
represented.

Describing the Needed Algorithms

• When solving a computational problem, either suitable existing algorithms may be found
or newalgorithms must be developed.
• For the MCGW problem, there are standard search algorithms that can be used.
• For the Traveling Salesman problem, there are various (nontrivial) algorithms that can be
utilized.
• Algorithms that work well in general but are not guaranteed to give the correct result for
each specific problem are called heuristic algorithms.
Step 3: Program Implementation

• Design decisions provide general details of the data representation and the algorithmic
approaches for solving a problem.
• The details, however, do not specify which programming language to use, or how to
implement the program. That is a decision for the implementation phase. Since we are
programming in Python, the implementation needs to be expressed in a syntactically
correct and appropriate way, using the instructions and features available in Python.
Step 4: Program Testing

• Programming errors are pervasive, persistent and inevitable.


• Testing is done incrementally as a program is being developed, when the program is
complete, and when the program needs to be updated.
• Any changes made in correcting a programming error should be fully understood as to
why the changes correct the detected error Truism 1 reflects the fact that programming
errors are inevitable and that we must accept it. As a result of truism 1, truism 2 states
the essential role of software testing.
• Given the inevitability of programming errors, it is important to test a piece of software in
a thorough and systematic manner.
• Finally, truism 3 states the importance of understanding why a given change (or set of
changes) in a program fixes a specific error.
3. ALGORITHM

1. Explain with an example the building blocks of an algorithm.(8MARKS) (JAN 2017)


2. Define algorithm.(2MARKS)(JAN 2019)
3. Summarize the characteristics of a good algorithm. (2MARKS) (APR 2019)
4. Distinguish between algorithm and program. (2MARKS) (JAN 2019)
5. Write an algorithm to accept two numbers, computer sum and print the result.
(2MARKS) (JAN 2022)
6. Outline the algorithm for displaying the first n odd numbers.(8MARKS)(JAN 2022)
7. Write a function to add two numbers. (2MARKS) (JAN 2022)

ALGORITHM:

Algorithm refers to the logic of the program. It is defined as a sequence of instructions


and if the instructions are executed in the specified sequence, then the desired result will be
obtained. It is defined as any problem whose solution can be expressed in a list of executable
instruction.

Characteristics:

• Instructions should be precise (exact and accurate) and unambiguous (expressed in a


clear way)
• Instructions should not be repeated infinitely.
• Algorithm should ultimately terminate.
• Instructions should be written in sequence.
• It should look like normal English.
• The desired result should be obtained only after the algorithm terminates.
• There are many methods or logics available to solve the problem. Therefore, for a given
problem, there are so many algorithms.

Qualities of a good algorithm:

The following are used to judge the quality of the algorithm.


• Time: The computer takes some amount of time for the execution of a program. The
lesser is the time required, the better is the algorithm
• Memory: The computer takes some amount of memory storage to execute a program.The
lesser is the memory requires, the better is the algorithm
• Accuracy: Multiple algorithms provide solutions to a given problem, but some provide
more accurate results than others, such algorithms may be suitable.

• Sequence: The instructions of an algorithm must form in a sequence or repeated a no. Of


times until a particular condition is met.
• Generality: The designed algorithm must handle a range of input data. So the
algorithms must be generalized.

Representation of Algorithms:

The algorithm can be represented in any one of the following ways:


• Normal English: The algorithm is represented step by step in normal English. Such
algorithms are easy to understand, read and write.
• Flow chart: The flow chart is a pictorial representation of an algorithm. The steps are
represented using the standard symbols in flow chart. It is a formal design tool.
• Pseudo code: It is also a formal design tool and utilized very well with rules of structured
design and programming.
• Decision table: It provides an easy look at a complex, nested selection to help clarify the
conditions to be tested and how those conditions should be nested to arrive at the proper
actions.
• Program: The algorithms can be represented using any high-level language, called as
program.

BUILDING BLOCKS OF AN ALGORITHM:

An algorithm is a sequence of simple steps that can be followed to solve a problem.


Algorithms can be designed using the following basic methods.
• Statements
• State
• Sequence
• Selection / Conditional
• Control flow
• Functions

An algorithm is an effective procedure for solving a problem in a finite number of steps. An


algorithm is a series of specific steps which solve a particular problem.

Series – The steps must be in particular order and each of the steps must be used.
Specific – A step must not be replaced by similar step.
Steps – Each action to be done is a step.
Solve – An algorithm produces final result or output which is the solution to the problem.
Particular problem – The algorithm for one problem will not usually solve a different
problem.
Statements-Most algorithms have these basic statements.
Description of the problem-Setup, Parameters, Execution, Conclusion

Example1: To find the sum of 2 numbers

Description of the problem: To find the sum of two numbers.


Setup- Two numbers are required for addition and one variable to store the result
Parameters- read the first number. Read the second number
Execution- Calculate the sum of two numbers read.
Conclusion- The desired output is given.
Sequential Control-Steps of an algorithm are carried out in a sequential manner, which
each step isexecuted exactly once.

Example2: Temperature Conversion- To convert temperature in Fahrenheit degree to


Celsius degree.
Algorithm:
Start
Read the temperature in Fahrenheit
Apply the conversion formula
Celsius degree = (5/9)*(Fahrenheit_degree-32)
Display the result
Stop
Statements:

Statement is a single action in a computer.


In a computer statements might include some of the following actions
• Input data-information given to the program
• Process data-perform operation on a given input
• Output data-processed result

State:

Transition from one process to another process under specified condition with in a time is
called state.

Control flow:

The process of executing the individual statements in a given order is called control flow.
The control can be executed in three ways
1. Sequence
2. Selection
3. Iteration

Sequence:

All the instructions are executed one after another is called sequence execution.
Example: Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop

Selection:

A selection statement causes the program control to be transferred to a specific part of the
program based upon the condition. If the conditional test is true, one part of the program will be
executed, otherwise it will execute the other part of the program.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop

Iteration:

In some programs, certain set of statements are executed again and again based upon
conditional test. i.e. executed more than one time. This type of execution is called looping or
iteration.

Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop

Selection / Conditional Control:

• Based on the condition, only one of a number of alternative steps is executed.

Example 1: To find the greatest of two numbers.


Algorithm:
Start
Read tow numbers A, B
Compare A and B. If A is greater perform step 4 else perform step 5.
Output A is greatest
Output B is greatest
Stop

Example 2: To find the greatest among three numbers.


Start
Read three numbers A, B and C
Compare A and B. If A is greater perform step 4 else perform step 5
Compare A and C. If A is greater, Output A is greatest else output C is greatest.
Compare B and C. If B is greater output B is greatest else output C is greatest.
Stop

Repetition or Control flow:

One or more steps are performed repeatedly. One or more instructions may be
executed several times depending on some conditions.
Example: To compute and print the sum and average of ten numbers.
Start
Initialize variables sum and avg to be 0
Repeat step 4 and step 5 for 10 times
Read the value of number
Add the value of the number to the sum
Calculate the average using avg=sum/10
Print the sum and avg value.
Stop

Functions:

• Function is a sub program which consists of block of code(set of instructions) that


performs a particular task.
• For complex problems, the problem is been divided into smaller and simpler tasks during
algorithm design.
• Complex problems can be solved by dividing the task into smaller and simpler tasks
during algorithm design. A function is a block of organized, reusable code. It provides
better modularity and high degree of code reusing.
• Different programming languages name functions differently, for e.g.) methods,
procedures, subroutines, etc.
• A function is a block of organized, reusable code that is used to perform a single, related
action. Function is also named as methods, sub-routines.

Benefits of Using Functions

• Reduction in line of code


• code reuse
• Better readability
• Information hiding
• Easy to debug and test
• Improved maintainability

Example:
Algorithm for addition of two numbers using function

Main function ()
Step 1: Start
Step 2: Call the function add ()
Step 3: Stop

sub function add()


Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
Elements of functions:

• Name for declaration of function


• Body consisting local declaration and statements
• Formal parameter
• Optional result type.

Basic Syntax
function name(parameters) function statementsend function

Algorithm for addition of two numbers using functionMain function ()


Step 1: Start
Step 2: Call the function add ()
Step 3: Stop
sub function add ()
Step1: Function start Step2: Get a, b Values
Step 3: add c=a + bStep 4: Print c
Step 5: End Function

4. NOTATIONS

1. Draw a flow chart to print the first ‘n’ prime numbers. (8MARKS) (JAN 2017)
2. Present the flow of execution for a while statement. (2MARKS) (JAN 2019)
3. List the symbols used in drawing a flowchart. (2MARKS)(APR 2019)
4. Draw a flowchart to accept three distinct numbers, find the greatest and print the result.
(8MARKS)(JAN 2022)
5. Draw a flowchart to find the sum of the series. (8MARKS)(JAN 2022)
1+2+3+……+100

A notation is a system of characters, expressions, graphics or symbols, design used in


problem solving to represent technical facts. Two notations are
• Pseudocode
• Flowchart
PSEUDOCODE:

Pseudocode is a formal design tool. It is also a programming analysis tool, that is,
commonly used in planning the program logic, where ‘pseudo’ means ‘initiation’, ‘code’ means
the set of statements or instructions written in programming language. It is also called as
‘Program Design language (PDL)’. During the design of Pseudocode, the designer or programmer
concentrate only on the logic of the program without worrying about the syntax of the
instructions. Hence pseudocode cannot be understood by the computer.

Pseudocode is a shorthand way of describing a computer program. Using pseudocode, it is


easier for a non- programmer to understand the general working of the program since it is not
based on any programming language. Pseudocode cannot be compiled or executed. Thus, there
is no standard for the syntax of Pseudocode. Some terms are commonly used in pseudocode to
represent various actions.

Examples:

To input the data – INPUT, GET, READY, READ


To output the data – OUTPUT, PRINT, DISPLAY
For calculations – COMPUTE, CALCULATE
For addition – ADD
For subtraction – SUB
For multiplication-MUL
For division-DIV
For incrementation – INCREMENT
For initialization – INITIALIZE

The following control structures are also used while writing the Pseudocode

• Sequence
• Selection / condition
• Iteration

Sequence:

The sequence structure is simply a sequence of steps to be executed in a linear order.


Example: To find the product of any two numbers
READ A, B
COMPUTE C by multiplying A with B
PRINT the result C
STOP

Selection or Conditional:

In selection, the step to be executed next is based on a decision taken. There are 2main
selection constructs – if-statement and case statement. In the if-statement, if the condition is
true then the THEN part is executed otherwise the ELSE part is executed. The case statement
is used when there are number of conditions to be checked. Depending on the value of
expression, one of the conditions is true, and the corresponding statements are executed. If
no match, then the OTHERS option which is also the default option is executed.
IF-statement
IF(condition) THEN
Statement
ENDIF

IF-ELSE statement
IF (condition) THEN
Statement 1
ELSE Statement 2
ENDIF

Example: To find the maximum of three numbers


Pseudocode:
READ values of A, B, C
IF A is greater than B and A is greater than C
THEN PRINT A is greatest
ELSEIF B is greater than C
PRINT B is greatest
ELSE
PRINT C is greatest
ENDIF
STOP

Case statement
CASE expression
Condition 1: Statement 1

Condition 2: Statement 2
..
..
Condition N: Statement N
OTHERS: default statement

Example: To print student’s grade based on the mark.

INPUT mark
CASE based on mark
CASE mark>=90 PRINT Grade S
CASE mark>=80 PRINT Grade A
CASE mark>=70 PRINT Grade B
CASE mark>=60 PRINT Grade C
CASE mark>=55 PRINT Grade D
CASE mark>=50 PRINT Grade E
OTHERS PRINT Fail

Iteration:

• Iteration is used in the place where repetition of several lines of code is necessary.
• For, while and do-while are the iterative statements.
• For loop, repeats the execution of the statements for the specified number of times.
For count=min to max
Statements
Next count

Example: To add first 10 numbers


INITIALIZE Total=0
For count=1 to 10
READ number
Total=Total + number
NEXT count
PRINT Total

WHILE loop execute the statements while the condition is true. In a WHILE loop thecondition is
checked at the start of the loop whereas in a DO- WHILE loop the condition is checked at the end
of the loop. So, the DO-WHILE loop executes at least once even if the condition is false when the
loop is entered.

WHILE (Condition)
Statement 1
Statement 2
..
ENDWHILE
Example: To add from 1 to 100
INITIALIZE SUM to ZERO
INTIALIZE I to ZERO
WHILE (I less than equal to 100)
INCREMENT I
ADD I to SUM and store in SUM
ENDWHILE
PRINT SUM
STOP

FLOW CHART

• A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart is


drawn using boxes of different shapes with lines connecting them to show the flow of
control. A flowchart represents the logic of the program clearer in a much better way
using a flowchart.
• A graphical representation of an algorithm.
• Flowcharts is a diagram made up of boxes, diamonds, and other shapes, connected by
arrows. Each shape represents a step-in process and arrows show the order in which
they occur.

Flowchart Symbols: A flowchart is drawn using different kinds of symbols. A symbol used in
the flowchart is for a specific purpose. The flowchart symbols are available in most word
processors facilitating the programmer to draw a flowchart on the computer using word
processor.
Table 1: Flowchart Symbols
S.No Name of Symbol Type Description
symbol
1. TerminalSymbol Oval Represent the start and stop of the
program.

2. Input/ Output Parallelogram Denotes either input or output


symbol operation.

3. Process symbol Rectangle Denotes the process to be carried

4. Decision symbol Diamond Represents decision making,


branching

5. Flow lines Arrow lines Represents the sequence of steps and


direction of flow. Used to connect
symbols.

6. Connector Circle A connector symbol is represented


by a circle and a letter or digit is
placed in the circle to specify thelink.
This symbol is used to connect
flowcharts.

Rules for drawing flowchart:

• In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
• The flow chart should be clear, neat and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
• The usual directions of the flow of a procedure or system is from left to right or top to
bottom.
• Only one flow line should come out from a process symbol.
• Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, cap leave the decision symbol.
• Only one flow line is used in conjunction with terminal symbol.
• If flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines.
• Ensure that flowchart has logical start and stop.

Advantages of Flowchart:

• Communication: Flowcharts are better way of communicating the logic of the system.
• Effective Analysis: With the help of flowchart, a problem can be analyzed in more
effective way.
• Proper Documentation: Flowcharts are used for good program documentation, which
is neededfor various purposes.
• Efficient Coding: The flowcharts act as a guide or blue print during the system analysis
andprogram development phase.
• Systematic Testing and Debugging: The flowchart helps in testing and debugging the
program
• Efficient Program Maintenance: The maintenance of operating program becomes easy
with the help offlowchart. It helps the programmer to put efforts more efficiently on that
part.

Disadvantages of Flowchart:

• Complex Logic: Sometimes, the program logic is quite complicated. In that case
flowchart becomes complex and difficult to use.
• Alteration and Modification: If alterations are required the flowchart may require re-
drawing completely.
• Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
• Sequence: In a sequence, the steps are executed in linear order one after the other.

Sequence Example: To find product of any 2 numbers:

Selection:

In a selection operation, the step to be executed next is based on a decision taken. If the
condition is true (yes), a path is followed and if the condition is false (no), then a different path
is followed.
Example1: To find the maximum of any three numbers
Example2: To display the grade for the marks obtained

Iteration:

In iterative operation, a condition is checked. Based on the result of this conditional check
(true or false), different paths are followed. Either the next step in the sequence is executed or
the control goes to one of the already executed steps to make a loop. In for loop, the statements
are repeated for specified number of times. Loop starts at min and ends with max. It has
incrementation part where the no. Of times the loop is executed is incremented. It has a
condition check part, which checks whether the loop has to be repeated or not.
Example: To add 10 numbers
while and do-while loop executes the statement while the condition is true.

while loop: do-while loop:

Example: To find the sum of first 100 integers.

Programming Language:

• A programming language is a vocabulary and set of grammatical rules for instructing a


computer or computing device to perform specific tasks. In other word it is set of
instructions for the computer tosolve the problem.
• Programming Language is a formal language with set of instruction, to the computer to
solve a problem.The program will accept the data to perform computation.
Program=Algorithm + Data
Need for Programming Languages

• Programming languages are also used to organize the computation


• Using Programming language, we can solve different problems
• To improve the efficiency of the programs.

Types of Programming Language

In general Programming languages are classified into three types. They are
• Low – level or Machine Language
• Intermediate or Assembly Language
• High – level Programming language

Machine Language

Machine language is the lowest-level programming language (except for computers


that utilize programmable microcode). Machine languages are the only languages understood by
computers. It isalso called as low-level language. Example code: 100110011 111001100

Assembly Language

An assembly language contains the same instructions as a machine language, but the
instructions and variables have names instead of being just numbers. An assembler language
consists of mnemonics, mnemonics that corresponds unique machine instruction.
Example: add x,y, sub x,y, start

High – level Language:

A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal


that enables a programmer to write programs that are more or less independent of a particular
type of computer. Such languages are considered high-level because they are closer to human
languages and further from machine languages. Ultimately, programs written in a high-level
language must be translated into machine language by a compiler or interpreter. Example code:
print (“Hello World!”)

High level programming languages are further divided as mentioned below.

Language Type Example


Interpreted Programming Language Python, BASIC, Lisp
Functional Programming Language Clean, Curry, F#
Compiled Programming Language C++,Java, Ada, ALGOL
Procedural Programming Language C,Matlab, CList
Scripting Programming Language PHP, Apple Script, Javascript
Markup Programming Language HTML,SGML,XML
Logical Programming Language Prolog, Fril
Concurrent Programming Language ABCL, Concurrent PASCAL
Object Oriented Programming Language C++,Ada, Java, Python
Interpreted Programming Language:

• Interpreter is a program that executes instructions written in a high-level language.


• An interpreter reads the source code one instruction or one line at a time, converts
thisline into machine code and executes it.

Figure: Interpreter

Compiled Programming Languages:

• Compile is to transform a program written in a high-level programming language


from source code into object code.
• This can be done by using a tool called compiler.
• A compiler reads the whole source code and translates it into a complete machine code
program to perform the required tasks which is output as a new file.

Figure: Compiler

Interpreted vs. Compiled Programming Language

Interpreted Programming Language Compile Programming Language


Translates one statement at a time Scans entire program and translates it as
whole
into machine code
It takes less amount of time to analyzethe It takes large amount of time to analyze
source code but the overall execution the
timeis slower source code but the overall execution
timeis comparatively faster
No intermediate object code is generated, Generates intermediate object code
hence are memory efficient which
further requires linking, hence requires
morememory
Continues translating the program until It generates the error message only after
first error is met, in which case it stops. scanning the whole program. Hence
Hencedebugging is easy. debugging
is comparatively hard.
Eg: Python, Ruby Eg: C, C++, Java
5. ALGORITHMIC PROBLEM SOLVING

1. Describe method of specifying an algorithm. ( 8MARKS)(APR 2019)


2. Define recursion with an example. ( 2 MARKS) (JAN2019)
3. Identify the simple strategies for developing an algorithm. (8 MARKS)(JAN2019)
4. Define understanding of a problem. (2 MARKS)(JAN2022)
5. Define an iterative statement. (2 MARKS) (JAN 2022)
6. Name the two types of iterative statements supported by python.(2 MARKS)(JAN 2022)

ALGORITHMIC PROBLEM SOLVING:

Algorithmic problem solving can be approached starting with an informal notion of an


algorithm. When solving a problem, choosing the right approach is often the key to arriving at
the best solution. In psychology, one of these problem-solving approaches is known as an
algorithm. While often thought of purely as a mathematical term, the same type of process can
be followed in psychology to find the correct answer when solving a problem or making a
decision.

Understanding the Problem

• It is the process of finding the input of the problem that the algorithm solves.
• It is very important to specify exactly the set of inputs the algorithm needs to handle.
• A correct algorithm is not one that works most of the time, but one that works Correctly
for alllegitimate inputs.

Ascertaining the Capabilities of the Computational Device

• If the instructions are executed one after another, it is called sequential algorithm
Choosingbetween Exact and Approximate Problem Solving
• The next principal decision is to choose between solving the problem exactly or solving it
approximately.
• Based on this, the algorithms are classified as exact algorithm and approximation
algorithm. Data structure plays a vital role in designing and analysis the algorithms. Some
of the algorithm design techniques also depend on the structuring data specifying a
problem’s instance

Algorithm+ Data structure=Program

Algorithm Design Techniques

An algorithm design technique (or “strategy” or “paradigm”) is a general approach to


solving problems algorithmically that is applicable to a variety of problems from different areas
of computing.Learning these techniques is of utmost importance for the following reasons.
First, they provide guidance for designing algorithms for new problems, Second, algorithms are
the cornerstone of computer science.

Methods of Specifying an Algorithm

• Pseudocode is a mixture of a natural language and programming language-like


constructs. Pseudocode is usually more precise than natural language, and its usage often
yields moresuccinct algorithm descriptions.
• In the earlier days of computing, the dominant vehicle for specifying algorithms was a
flowchart, a method of expressing an algorithm by a collection of connected geometric
shapescontaining descriptions of the algorithm’s steps.
• Programming language can be fed into an electronic computer directly. Instead, it needs
to be converted into a computer program written in a particular computer language. We
can look at such a program as yet another way of specifying the algorithm, although it is
preferable to consider it as the algorithm’s implementation.
• Once an algorithm has been specified, you have to prove its correctness. That is, you have
to prove that the algorithm yields a required result for every legitimate input in a finite
amount oftime.
• A common technique for proving correctness is to use mathematical induction because an
algorithm’s iterations provide a natural sequence of steps needed for such proofs.
• It might be worth mentioning that although tracing the algorithm’s performance for a few
specific inputs can be a very worthwhile activity, it cannot prove the algorithm’s
correctness conclusively. But in order to show that an algorithm is incorrect, you need
just one instance ofits input for which the algorithm fails.

Analyzing an Algorithm:

• Efficiency
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses
• Simplicity
An algorithm should be precisely defined and investigated with mathematical
expressions.
Simpler algorithms are easier to understand and easier to program.
Simple algorithms usually contain fewer bugs.

Coding an Algorithm:

• Most algorithms are destined to be ultimately implemented as computer programs.


Programming an algorithm presents both a peril and an opportunity.
• A working program provides an additional opportunity in allowing an empirical analysis
of the underlying algorithm. Such an analysis is based on timing the program on several
inputs and then analyzing the results obtained.

SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:

They are two commonly used strategies used in developing algorithm


• Iteration
• Recursion

Iteration:

• The iteration is when a loop repeatedly executes till the controlling condition becomes
false
The iteration is applied to the set of instructions which we want to get repeatedly executed.
• Iteration includes initialization, condition, and execution of statement within loop and
update(increments and decrements) the control variable.
• A sequence of statements is executed until a specified condition is true is called iterations.
for loop, While loop
Recursions:

• A function that calls itself is known as recursion.


• Recursion is a process by which a function calls itself repeatedly until some specified
conditionhas been satisfied.

Syntax FOR Example: Print n natural numbers


BEGINGET n
FOR(variable) IN limit INITIALIZE i=1FOR i IN n PRINT i
statement i=i+1ENDFOREND
... ENDFOR
Syntax for While: Example: Print n natural numbers
BEGINGET n
WHILE (condition) DOstatement INITIALIZE i=1WHILE(i<=n) DOPRINT i
... i=i+1
EXAMPLE ENDWHILE ENDWHILE
: END

Algorithm for factorial of n numbers using recursion:

Main function:

Step1: Start Step2: Get n


Step3: call factorial (n)
Step4: print fact
Step5: Stop

Sub function factorial (n):

Step1: if(n==1) then fact=1 return fact


Step2: else fact=n*factorial (n-1) and return fact

Pseudo code for factorial using recursion:

Main function:

BEGIN
GET nCALL
factorial (n)
PRINT factEND

Sub function factorial (n):

IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial (n-1)
Flow Chart

6. ILLUSTRATIVE PROBLEMS

1. Write a recursive algorithm to solve Towers of Hanoi problem. (8MARKS) (JAN 2019)
2. Write an algorithm to insert a card in a list of sored cards. (8MARKS) (JAN 2019)
3. State the Towers of Hanoi problem. Outline a solution to the Towers of Hanoi problem with
relevant diagrams . (8MARKS) (JAN 2022)

GUESS AN INTEGER IN A RANGE


Algorithm:

Start
Declare hidden, guess, range = 1 to 100
Compute hidden = Choose a random value in a range
Read guess
If guess = hidden, then print “Guess is hit” else print “Guess not hit”
Stop

Pseudocode:

INITIALIZE hidden = randomnumber


READ guess
IF (guess == hidden)
THEN
PRINT Guess is hit
ELSE
PRINT Guess not hit
END IF
Flowchart
FIND MINIMUM IN A LIST

Algorithm:

Start
Read n
Initialize i=0
If i < n, then goto step 5 and 6 else goto step 7
Read a[i]
i=i+1 goto step 4
Compute min=a [0]
Initialize i=1
If i < n, then go to step 10 else goto step 14
If a[i] < min, then goto step 11, 12 else goto 12
min=a[i]
i=i+1 goto 7
Print min
Stop

Pseudocode:

READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, THEN
CALCULATE min=a[i]
INCREMENT i
ELSE
PRINT min
ENDIF
END FOR
Flowchart:
INSERT A CARD IN A LIST OF SORTED CARDS

Problem Description:

Finding minimum in a list Problem description: The problem is to find the minimum
element in the given list of elements. Finding minimum in a list of elements can be achieved in
different ways. One way is to sort the list of elements in ascending order and get the first
element as minimum. Another method is to compare each element with other. As an initial step,
first element of the list is considered as minimum element. And in each iteration, each element in
the list is compared with the minimum. If the element in the list is less than the minimum then
swap both elements else compare with the next element in the list. These steps are continued
until the end of the list and finally print the minimum.

Algorithm:

Start
Read n
Initialize i=0
If i<n, then goto step 5, 6 else goto step 7
Read a[i]
i=i+1 goto step 4
Read item
Calculate i=n-1
If i>=0 and item<a[i], then go to step 10, 11 else goto step1210. a[i+1]=a[i]
i=i-1 goto step 7
Compute a[i+1]=item
Compute n=n+1
If i<n, then goto step 15, 16 else goto step 16
Print a[i] and increment i and goto step 14
Stop

Pseudocode:

READ n
FOR i=0 to n
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i] THEN
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n,
PRINT a[i]
INCREMENT i
END FOR
Flowchart:
TOWER OF HANOI

Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C)
and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest
disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire
stack to another rod (here considered C).
Rules:
• Only one disk can be moved at a time.
• Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
• No disk may be placed on top of a smaller disk.
The steps are
i) Move the top n-1 disks from the left pole to the centre pole, n is the number of disks.
ii) Move the nth largest disk to the right pole.
iii) Move the n-1 disks on the centre pole to the right pole.

The total number of moves will be 2 n – 1, where n is the number of disks.


Algorithm

Start
Read n
Calculate move=pow(2,n)-1
Function call T(n,Beg,Aux,End)
recursively until n=0
If n=0, then goto step 9
else goto step 6
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End) # Move disk from source to destination
T(n-1,Aux,Beg,End)
Stop

Pseudocode:

READ n
CALCULATE move=pow(2,n)-1

FUNCTION T(n,Beg,Aux,End)
Recursively until n=0
PROCEDURE
IF n==0
THEN
No disk to move
ELSE
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End)#move disk from source to destination
T(n-1,Aux,Beg,End)
END IF
END PROCEDURE
Flowchart:

You might also like