You are on page 1of 46

LECTURE NOTES

ON

PROBLEM SOLVING
AND
PROGRAMMING
(R204GA05101)

I B.TECH I SEMESTER
Regulation: R20

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


SRINIVASA RAMANUJAN INSTITUTE OF TECHNOLOGY
(Affiliated to JNTUA & Approved by AICTE)
Rotarypuram Village, B K Samudram Mandal, Ananthapuramu - 515701.

(2020 – 2021)
Problem Solving & Programming

UNIT – I
Introduction to Programming, Algorithms, Flowcharts and C Programming

Programs and Programming, Programming languages, Compiler, Interpreter, Loader, Linker,


Program execution, Fourth generation languages, Fifth generation languages, Classification of
Programming languages, Structured Programming concept, Algorithms, Pseudo-code,
Flowcharts, Strategy for designing algorithms, Tracing an algorithm to depict logic,
Specification for converting algorithms into programs.

Introduction, standardization of C Language, developing programs in C, a simple C program,


parts of C Program and revisited structure of a C Program.

Learning Outcomes:
At the end of unit, students will be able to
1. Understand the generations and classification of programming languages.
2. Solve complex problems using language independent notations.
3. Illustrate the steps in compilation of a C Program.

1. Generations of Computers

1.1 First Generation Computers: Period: (1946-1959)


Technology: Vacuum tubes
The ENIAC (Electronic Numerical Integrator and Calculator) was the first computer
developed in this generation. It was capable of performing 5000 additions (or) 350
multiplications per second. It uses about 18000 vacuum tubes and it consumes 150 kw/hr.
Limitations:
The limitations of first generation computers are as follows.
 Less operating capacity.
 High power consumption.
 Very large space requirement.
 Produce high temperature.
 Very costly.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 2


Problem Solving & Programming

1.2 Second Generation Computers: Period: (1959-1965)


Technology: Transistors
The second generation computers use transistors as the main component in CPU. They
are very small in size when compared to vacuum tubes and produce less heat. They are fast
and reliable.
Due to this invention of Transistors the size, maintenance cost, power consumption has
decreased.
During this period magnetic storage devices have been started there development. Because
of this, speed and storage capacity has been increased. They are capable of performing
20,000 to 50,000 additions per second.

1.3 Third Generation Computers: Period: (1965-1971)


Technology: Integrated Circuits (IC)
In this generation the computers used integrated circuits instead of Transistors.
Integrated circuit is a miniature form of an electronic circuit made of silicon and enclosed in
a metal package.
These IC’s are caused “chips.” The cost and size of the computers were greatly reduced.
The magnetic disk technology has improved rapidly. It has capable to perform 10 million
additions per second.

1.4 Fourth Generation Computers: Period: (1971-1980)


Technology: Very Large Scale Integrated Circuit (VLSI)
IC’s packing nearly 10,000 transistors are grouped in to a single silicon chip known as
“microprocessor”. The computers which use micro processors are called “Micro Computers”.
Intel Corporation invented the micro processor in the year 1980 with this development the
cost of a computer has reduced a lot.
The floppy disk technology was developed during this generation.

1.5 Fifth Generation Computers: Period: (1980 onwards)


Technology: Uni Large Scale Integrated Circuits (ULSI)
Artificial Intelligence is a technique by which we make the computer to think and take
decisions in its own.
These computers are under research.
Artificial Intelligence can be achieved by means of problem solving, Game playing, and
Expert systems.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 3


Problem Solving & Programming

2. Computer
Computer is a fast electronic device that takes raw data as input from the user, processes
it according to the set of stored instructions (called program), gives the result (output). It
is designed to execute applications and provides a variety of solutions by combining
integrated hardware and software components. A computer is made up of multiple parts
and components that facilitate user functionality.

Functionalities of a computer:
Any digital computer carries out five functions in gross terms:
 Takes data as input.
 Stores the data/instructions in its memory and use them when required.
 Processes the data and converts it into useful information.
 Generates the output
 Controls all the above four steps.

3. Computer – Memory
A memory is just like a human brain. It is used to store data and instructions. Computer
memory is the storage space in computer where data is to be processed and instructions
required for processing are stored. The memory is divided into large number of small parts
called cells. Each location or cell has a unique address which varies from zero to memory size
minus one. For example if computer has 64k words, then this memory unit has 64 *
1024=65536 memory locations. The address of these locations varies from 0 to 65535.
Memory is primarily of three types
 Cache Memory
 Primary Memory/Main Memory
 Secondary Memory

Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up CPU. It acts as
a buffer between the CPU and main memory. It is used to hold those parts of data and
program which are most frequently used by CPU. The parts of data and programs are
transferred from disk to cache memory by operating system, from where CPU can access
them.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 4


Problem Solving & Programming

Advantages
The advantages of cache memory are as follows:
 Cache memory is faster than main memory.
 It consumes less access time as compared to main memory.
 It stores the program that can be executed within a short period of time.
 It stores data for temporary use.
Disadvantages
The disadvantages of cache memory are as follows:
 Cache memory has limited capacity.
 It is very expensive.

Primary Memory (Main Memory)


Primary memory holds only those data and instructions on which computer is currently
working. It has limited capacity and data is lost when power is switched off. It is generally
made up of semiconductor device. These memories are not as fast as registers. The data and
instruction required to be processed reside in main memory. It is divided into two
subcategories RAM and ROM.

Characteristics of Main Memory


 These are semiconductor memories
 It is known as main memory.
 Usually volatile memory.
 Data is lost in case power is switched off.
 It is working memory of the computer.
 Faster than secondary memories.
 A computer cannot run without primary memory.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 5


Problem Solving & Programming

Secondary Memory
This type of memory is also known as external memory or non-volatile. It is slower than main
memory. These are used for storing data/Information permanently. CPU directly does not
access these memories instead they are accessed via input-output routines. Contents of
secondary memories are first transferred to main memory, and then CPU can access it.
For example: disk, CD-ROM, DVD etc.
Characteristic of Secondary Memory

 These are magnetic and optical memories


 It is known as backup memory.
 It is non-volatile memory.
 Data is permanently stored even if power is switched off.
 It is used for storage of data in a computer.
 Computer may run without secondary memory.
 Slower than primary memories.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 6


Problem Solving & Programming

4. Programs and Programming:


 A program is a set of logically related instructions that is arranged in a sequence to
solve a particular problem. The process of writing a program is called programming.
 It is a necessary and critical step in data processing.
There are two ways for acquiring a program—either purchase an existing program, referred
to as packaged software or prepare a new program from scratch, in which case it is called
customized software.

4.1 Computer Software

Software is a set of programs, which is designed to perform a well-defined function. A


program is a sequence of instructions written to solve a particular problem.
There are two types of software
 System Software
 Application Software

4.1.1 System Software


The system software is collection of programs designed to operate, control, and extend
the processing capabilities of the computer itself. System software are generally prepared by
computer manufactures. These software products comprise of programs written in low-level
languages which interact with the hardware at a very basic level. System software serves as
the interface between hardware and the end users.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 7


Problem Solving & Programming

Some examples of system software are Operating System, Compilers, Interpreter, Assemblers
etc.

Features of system software are as follows:


 Close to system
 Fast in speed
 Difficult to design
 Difficult to understand
 Less interactive
 Smaller in size
 Difficult to manipulate
 Generally written in low-level language

4.1.2 Application Software


Application software products are designed to satisfy a particular need of a particular
environment. All software applications prepared in the computer lab can come under the
category of Application software.

Application software may consist of a single program, such as a Microsoft's notepad for
writing and editing simple text. It may also consist of a collection of programs, often called a
software package, which work together to accomplish a task, such as a spreadsheet package.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 8


Problem Solving & Programming

Examples of Application software are following:


 Payroll Software
 Student Record Software
 Inventory Management Software
 Income Tax Software
 Railways Reservation Software
 Microsoft Office Suite Software
 Microsoft Word
 Microsoft Excel
 Microsoft PowerPoint

Features of application software are as follows:


 Close to user
 Easy to design
 More interactive
 Slow in speed
 Generally written in high-level language
 Easy to understand
 Easy to manipulate and use
 Bigger in size and requires large storage space

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 9


Problem Solving & Programming

5. Programming languages
A programming language is composed of a set of instructions in a language understandable to
the programmer and recognizable by a computer.
Programming languages can be classified as
1. High-Level
2. Middle-Level
3. Low-Level

High-level languages such as BASIC, COBOL (Common Business Oriented Programming


Language), and FORTRAN (Formula Translation Language) are used to write application
programs.
A middle-level language such as C is used for writing application and system programs.
A low-level language such as the assembly language is mostly used to write system programs.
Low-level programming languages were the first category of programming languages to
evolve. Gradually, high-level and middle-level programming languages were developed and
put to use.

5.1 Low-level Languages


A low-level computer programming language is one that is closer to the native
language of the computer, which is 1’s and 0’s.
Machine language
This is a sequence of instructions written in the form of binary numbers consisting of
1’s and 0’s to which the computer responds directly. A machine language instruction generally
has three parts as shown in Fig. The first part is the command or operation code that conveys
to the computer what function has to be performed by the instruction. All computers have
operation codes for functions such as adding, subtracting and moving. The second part of the
instruction either specifies that the operand contains data on which the operation has to be
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 10
Problem Solving & Programming

performed or it specifies that the operand contains a location, the contents of which have to
be subjected to the operation. Machine language is considered to be the first generation
language (1GL).

Advantage of machine language


 It is easily understood by the computer
 The time taken to execute the program is very less
 The computation speed is very high

Disadvantages of machine language


 Difficult to use: It is difficult to understand and develop a program using machine
language
 Machine dependent: The programmer has to remember machine characteristics
while preparing a program. As the internal design of the computer is different across e
ALU, CU, and size of the word length of the memory unit, the machine language also
varies from one type of computer to another.
 Error prone: It is hard to understand and remember the various combinations of 1’s
and 0’s representing data and instructions. This makes it difficult for a programmer to
concentrate fully on the logic of the problem, thus frequently causing errors.
 Difficult to debug and modify: Checking machine instructions to locate errors are
about as tedious as writing the instructions. Further, modifying such a program is
highly problematic.

5.2 Assembly language


 This is also considered to be a second generation language (2GL).
 When symbols such as letters, digits, or special characters are employed for the
operation, operand, and other parts of the instruction code, the representation is called
an assembly language instruction.
 Such representations are known as mnemonic codes. A program written with
mnemonic codes forms an assembly language program.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 11


Problem Solving & Programming

 Each computer has its own assembly language that is dependent upon the internal
architecture of the processor.
 An assembler is a translator that takes input in the form of the assembly language
program and produces machine language code as its output.

Advantage of assembly language


 Writing a program in assembly language is more convenient than writing one in
machine language.
 Instead of binary sequence, a program in assembly language is written in the form of
symbolic instructions. This gives the assembly language program improved readability
Disadvantages of assembly language
 Assembly language is specific to particular machine architecture, i.e., machine
dependent.. This means that assembly language programs written for one processor
will not work on a different processor if it is architecturally different. That is why an
assembly language program is not portable.
 Programming is difficult and time consuming.
 The programmer should know all about the logical structure of the computer.

5.3 High-level Languages


 High-level programming languages such as COBOL, FORTRAN, and BASIC have
instructions that are similar to human languages and have a set grammar that makes it
easy for a programmer to write programs and identify and correct errors in them.
 The time and cost of creating machine and assembly language programs were quite
high. This motivated the development of high-level languages.

Advantages of high-level programming languages


 Readability: Programs written in these languages are more readable than those
written in assembly and machine languages
 Portability: High-level programming languages can be run on different machines with
little or no change
 Easy debugging: Errors can be easily detected and removed

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 12


Problem Solving & Programming

 Ease in the development of software: Since the commands of these programming


languages are closer to the English language, software can be developed with ease.
 High-level languages are also called third generation languages (3GLs).

6. Compiler, Interpreter, Loader, Linker


For executing a program written in a high-level language, it must be first translated
into a form the machine can understand. This is done by software called the compiler. The
compiler takes the high-level language program as input and produces the machine language
code as output for the machine to execute the program. This is illustrated in Fig. 1.8.

During the process of translation, the compiler reads the source program statement and
checks for syntax errors. In case of any error, the computer generates a report for the same.
This action is known as diagnostics.

Difference between Compiler and Interpreter

Compiler Interpreter
A compiler takes the entire program in An interpreter takes a single line of code
one go. at a time.
The compiler generates an intermediate The interpreter never produces any
machine code. intermediate machine code.
The compiler produces an output The interpreter does not produce any
program (.exe) that can be executed output program. Therefore, the execution
independently of the source program. requires a source program every time.
It is a two-step process as the program It is a one-step process because the
execution is segregated from the execution process is part of the
compilation. Execution begins only after interpretation that is done line by line.
the entire source-program is compiled.
We cannot change or modify anything in The interpreter uses the source code
the compiled program. To make changes, every time and works line by line;
we have to change the source code. Therefore, we can easily make changes.
The compiler displays all errors after The interpreter displays the errors of
compilation, which complicates the error each line one by one, if any, making it
detection and removal process. easier to detect and remove errors.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 13


Problem Solving & Programming

The compiler is best suited for the An interpreter is best suited for a
production environment. software development environment.
The compiler is used by programming An interpreter is used by programming
languages such as C, C ++, C #, Scala, Java, languages such as Python, PHP, Perl,
etc. Ruby, etc.

6.1 Compiling and Executing High-level Language Programs


Compiling:
 The compiling process consists of two steps: the analysis of the source program and
the synthesis of the object program in the machine language of the specified machine.
 The analysis phase uses the exact description of the source programming language. A
source language is described using lexical rules, syntax rules, and semantic rules.
 Lexical rules specify the valid syntactic elements or words of the language.
 Syntax rules specify the way in which valid syntactic elements are combined to form
the statements of the language.

The steps in the process of translating a source program in a high-level language to executable
code are depicted in above Figure

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 14


Problem Solving & Programming

The first block is the lexical analyzer. It takes successive lines of a program and breaks them
into individual lexical items namely, identifier, operator delimiter, etc. and attaches a type tag
to each of these. Beside this, it constructs a symbol table for each identifier. The symbol table
is used later to allocate memory to each variable.
The second stage of translation is called syntax analysis or parsing. In this phase,
expressions, declarations, and other statements are identified by using the results of lexical
analysis
In the semantic analysis phase, the syntactic units recognized by the syntax analyzer
are processed. An intermediate representation of the final machine language code is
produced.
The last phase of translation is code generation, when optimization to reduce the
length of machine language program is carried out. The output of the code generator is a
machine level language program for the specified computer, a final linking and loading step is
needed to produce the complete machine language program in an executable form.
The linker’s job is to find the correct main memory locations of the final executable program.
The loader then places the executable program in memory at its correct address.

Execution:
The execution of a program written in high-level language involves the following steps:
1. Translation of the program resulting in the object program.
2. Linking of the translated program with other object programs needed for execution,
thereby resulting in a binary program.
3. Relocation of the program to execute from the specific memory area allocated to it.
4. Loading of the program in the memory for the purpose of execution.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 15


Problem Solving & Programming

Linker
Linking resolves symbolic references between object programs. It makes object programs
known to each other. Linking makes the addresses of programs known to each other so that
transfer of control from one subprogram to another or a main program takes place during
execution.
Relocation
Relocation means adjustment of all address-dependent locations, such as address constant, to
correspond to the allocated space, which means simple modification of the object program.
Relocation is more than simply moving a program from one area to another in the main
memory.
Loader
A loader is a system program that accepts object programs and prepares them for execution
and initiates the execution. The functions performed by the loader are:
 Assignment of load-time storage area to the program
 Loading of program into assigned area
 Relocation of program to execute properly from its load time storage area
 Linking of programs with one another
A relocating loader may load a program at various places in primary storage depending on the
availability of primary storage area at the time of loading. A program may be relocated
dynamically with the help of a relocating register.

7. Program execution
 The primary memory of a computer, also called the Random Access Memory, is divided
into units known as words.
 Depending on the computer, a word of memory may be two, four, or even eight bytes
in size. Each word is associated with a unique address, which is a positive integer that
helps the CPU to access the word.
 Addresses increase consecutively from the top of the memory to its bottom.
 When a program is compiled and linked, each instruction and each item of data is
assigned an address.
 At execution time, the CPU finds instructions and data from these addresses. The PC, or
program counter, is a CPU register that holds the address of the next instruction to be
executed in a program.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 16


Problem Solving & Programming

 The CPU fetches the contents of the words addressed by the PC in the same amount of
time, whatever their physical locations.
 Program execution proceeds in this way until the CPU has processed the last
instruction.

8. Fourth generation languages:

The Fourth Generation Language is a non-procedural language that allows the user to
simply specify what the output should be without describing how data should be processed to
produce the result. A fourth generation language, commonly referred to as 4GL, is a high-level
language that requires significantly fewer instructions to accomplish a particular task than
does a third generation language. Thus, a programmer should be able to write a program
faster in 4GL than in a third generation language.

9. Fifth generation languages

Natural languages represent the next step in the development of programming


languages belonging to fifth generation languages. Natural language is similar to query
language, with one difference: it eliminates the need for the user or programmer to learn a
specific vocabulary, grammar, or syntax. Natural language takes the user one step further
away from having to deal directly and in detail with computer hardware and software. These
languages are also designed to make the computer smarter—that is, to simulate the human
learning process.

10. Classification of Programming languages

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 17


Problem Solving & Programming

10.1 Procedural Languages

Algorithmic languages: These are high-level languages designed for forming convenient
expression of procedures, used in the solution of a wide class of problems. In this language,
the programmer must specify the steps the computer has to follow while executing a program.
Some of languages that fall in the category are C, COBOL, and FORTRAN.

Object-oriented language: The basic philosophy of object oriented programming is to deal


with objects rather than functions or subroutines as in strictly algorithmic languages. Objects
are self-contained modules that contain data as well as the functions needed to manipulate
the data within the same module. The most important object-oriented programming features
are
 Abstraction
 encapsulation and data hiding
 polymorphism
 inheritance
 reusable code
C++, JAVA, SMALLTALK, etc. are examples of object oriented languages.

Scripting languages: These languages assume that a collection of useful programs, each
performing a task, already exists. It has facilities to combine these components to perform a
complex task. One of the earliest scripting languages is the UNIX shell. Now there are several
scripting languages such as VB script and Perl.

10.2 Problem-oriented Languages


These are high-level languages designed for developing a convenient expression of a given
class of problems.

10.3 Non-procedural Languages


Functional (applicative) languages: These functional languages solve a problem by applying
a set of functions to the initial variables in specific ways to get the answer. The functional
programming style relies on the idea of function application rather than on the notion of
variables and assignments. A program written in a functional language consists of function
calls together with arguments to functions. LISP, ML, etc. are examples of functional
languages.
Logic-based programming language: A logic program is expressed as a set of atomic
sentences, known as fact, and horn clauses, such as if-then rules. A query is then posed. The
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 18
Problem Solving & Programming

execution of the program now begins and the system tries to find out if the answer to the
query is true or false for the given facts and rules. Such languages include PROLOG.

11. Algorithms
Algorithm is a very popular technique used to obtain solution for a given problem.

Definition: An algorithm is defined as a finite set of steps that provide a chain of actions for
solving a problem.

Characteristics an algorithm:

An Algorithm is a well organized and textual computational module that receives one or more
input values and provides one or more output values.

 The steps are well defined and arranged in a sequence that processes given input into
output.
 The steps of the algorithm are written using English like statements which are easy to
understand.
 This will enable the reader to translate each step into a program.
 Every step is known as instruction.
 An algorithm is set to be accurate only when it provides the exact required output.
 If the procedure is lengthy then sub divided the procedure into small parts as it make
easy to solve the problem.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 19


Problem Solving & Programming

Analyzing an Algorithm:
When one writes an algorithm, it is essential to know how to analyses the algorithm.
Analyzing the algorithm refers to calculating the resources such as computer
memory, processing time, logic gates and so on …..
Time is most important resource because the program developed should be
faster in processing.
The analysis can also be made by reading the algorithm for logical accuracy, tracing the
algorithm and checking with the data.

11.1 Different Ways of Stating Algorithms


Algorithms may be represented in various ways. There are four ways of stating algorithms.
These are as follows:
 Step-form
 Pseudo-code
 Flowchart
 Nassi-Schneiderman
Step form: In the step form representation, the procedure of solving a problem is stated with
written statements. Each statement solves a part of the problem and these together complete
the solution. Every statement, that defines an action, is logically related to the preceding
statement.
Pseudo code: The pseudo-code is a written form representation of the algorithm. However it
differs from the step form as it uses a restricted vocabulary to define its action of solving the
problem
Flowchart and Nassi-Schneiderman: These are graphically oriented representation forms.
They use symbols and language to represent sequence, decision, and repetition actions.
Step Form:
For illustrating the step-form the following conventions are assumed:
 Each algorithm will be logically enclosed by two statements START and STOP.
 To accept data from user, the INPUT or READ statements are to be used.
 To display any user message or the content in a variable, PRINT statement will be used.
Note that the message will be enclosed within quotes.
 There are several steps in an algorithm. Each step results in an action. The steps are to
be acted upon sequentially in the order they are arranged or directed.
 The arithmetic operators that will be used in the expressions are
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 20
Problem Solving & Programming

‘←’ ….Assignment
‘+’….. Addition
‘–’….. Subtraction
‘*’….. Multiplication
‘/’….. Division
 Relational operators will include
‘>’ ….. Greater than
‘<=’ …..Less than or equal to
‘<’ …… Less than
‘=’ …… Equality
‘>=’ …… Greater than or equal to
‘!=’ …… Non- equality
 The most commonly used logical operators will be AND, OR and NOT.

Categories of Algorithms

The steps in an algorithm can be divided into three categories, namely

 Sequence Algorithms
 Selection Algorithms
 Repetition Algorithms

Sequence Algorithms
The steps described in an algorithm are performed successively one by one without skipping
any step.
The sequence of steps defined in an algorithm should be simple and easy to understand.
Example-1:
Algorithm: Calculating area and perimeter of a rectangle.
Input: Length and Width of a rectangle, assume len, wid
Output: Area and Perimeter of a rectangle, assume area, peri
1. BEGIN
2. READ len, wid of a rectangle
3. COMPUTE area as area= len x wid
4. COMPUTE peri as peri=2 x (len + wid)
5. DISPLAY area, peri
6. END
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 21
Problem Solving & Programming

Example-2:
Algorithm: Calculating Simple Interest
Input: Principal Amount, Time, Rate of Interest, assume p,t,r
Output: Simple Interest, assume si
1. BEGIN
2. READ p, t, r
3. COMPUTE si as si=(p x t x r) / 100
4. DISPLAY si
5. END

Selection Algorithms
We understand that the algorithms written in sequence fashion are not reliable. There must
be a procedure to handle operation failure occurring during execution.
The selection of statements can be shown as follows

if proposition then
Statement-1;
else
Statement-2;
The above syntax specifies that if the proposition is true, statement-1 will be
executed otherwise statement-2 will be executed.
In case the operation is unsuccessful. Then sequence of algorithm should be changed/
corrected in such a way that the system will re-execute until the operation is successful.

Example:
1. Write an algorithm to check person eligibility for vote.
Algorithm:
Input: Age of a person, assume age
Output: Eligible/Ineligible for vote
1. BEGIN
2. READ age
3. if age > = 18 then
goto step_4
else
goto step_5
4. PRINT “person is eligible for vote”
5. PRINT “ person is not eligible for vote”

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 22


Problem Solving & Programming

6. END

2. Write an algorithm to check a given number is even or odd.


Algorithm:
Input: Any number, Assume num
Output: Even or Odd
1. BEGIN
2. READ num
3. If num % 2 = 0 then
goto step-5
else
goto step-6
4. PRINT “ Given number is Even”
5. PRINT “ Given number is Odd”
6. END

Repetition Algorithms
To solve a given problem, sometimes it is required to perform the same selected action
for certain number of times. If the same statement is written repetitively, it will increase the
size of a program. To avoid this problem, iteration mechanism is applied.
The statement written in an iteration block is executed for a given number of times
based on the truth value (true/false) of a condition.
It is required to count the no. of iterations getting completed; we need to initialize
some counter to a suitable initial value. For example, to count no. of names entered by the
user, the counter must be initialized to either 1 or 10 provided if the no. of names to be read
are 10.
General Format:
Initialize counter to suitable initial value
Repeat
Statement(s)
Until condition
The above format specifies that the execution of statement(s) will be repeated until the
specified condition is TRUE, once it become FALSE, repetition stops and gets terminated.
The given condition will be evaluated for every repetition, the truthness of the condition will
decide whether to continue the next repetition or not.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 23


Problem Solving & Programming

Examples:
1. Write an algorithm to display your name for 10 times.
Algorithm:
Input: Your name, assume Computer Programming
Output: Name to be displayed for 10 times
1. BEGIN
2. Initialize counter to 1
3. REPEAT
PRINT “Computer Programming”
counter = counter + 1
4. UNTIL counter < = 10
5. END
2. Write an algorithm to find the sum of the following series.
Sum= 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
Algorithm:
Input: Given series
Output: sum of the given series, assume sum
1. BEGIN
2. Initialize term to 1, sum to 0
3. REPEAT
sum = sum + term
term = term + 1
4. UNTIL term >= 10
5. PRINT sum
6. END
3. Write an algorithm to find the factorial of a given number.
N! = 1 x 2 x 3 x 4 x ……………….. N
Ex: 5! = 1 x 2 x 3 x 4 x 5 = 120
Algorithm:
Input: Any number to find factorial, assume num.
Output: Factorial of given number, assume fact.
1. BEGIN
2. READ num
3. Initialize term to 1, fact to 1
4. REPEAT
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 24
Problem Solving & Programming

fact = fact x term


term = term + 1
5. UNTIL term >= num
6. PRINT fact
7. END

Algorithms for some other problems


Ex 1. Write the algorithm for finding the sum of any two numbers.
Solution Let the two numbers be A and B and let their sum be equal to C. Then, the desired
algorithm is given as follows:
1. START
2. PRINT “ENTER TWO NUMBERS”
3. INPUT A, B
4. C ← A + B //Add values assigned to A and B and assign this value to C
5. PRINT C
6. STOP
Explanation The first step is the starting point of the algorithm.
The next step requests the programmer to enter the two numbers that have to be added. Step
3 takes in the two numbers given by the programmer and keeps them in variables A and B.
The fourth step adds the two numbers and assigns the resulting value to the variable C. The
fifth step prints the result stored in C on the output device. The sixth step terminates the
procedure.

Ex 2. Construct the algorithm for interchanging the numeric values of two variables.
Solution Let the two variables be A and B. Consider C to be a third variable that is used to store the
value of one of the variables during the process of interchanging the values.
The algorithm for the given problem is as follows.
1. START
2. PRINT “ENTER THE VALUE OF A & B”
3. INPUT A, B
4. C ←A
5. A ←B
6. B ←C
7. PRINT A, B
8. END
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 25
Problem Solving & Programming

Ex 3. Write an algorithm that compares two numbers and prints either the message
identifying the greater number or the message stating that both numbers are equal.

Solution This example demonstrates how the process of selection or decision making is
implemented in an algorithm using the step form. Here, two variables, A and B, are assumed to
represent the two numbers that are being compared. The algorithm for this problem is given as
follows.

1. START
2. PRINT “ENTER TWO NUMBERS”
3. INPUT A, B
4. IF A > B THEN
PRINT “A IS GREATER THAN B”
5. IF B > A THEN
PRINT “B IS GREATER THAN A”
6. IF A = B THEN
PRINT “BOTH ARE EQUAL”
7. STOP

Ex 5. Print the largest number among three numbers.


Solution Let the three numbers be represented by A, B, and C. There can be three ways of
solving the problem. The three algorithms, with some differences, are given below.

1. START
2. PRINT “ENTER THREE NUMBERS”
3. INPUT A, B, C
4. IF A >= B AND B >= C
THEN PRINT A
5. IF B >= C AND C >= A
THEN PRINT B
6. ELSE
PRINT C
7. STOP

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 26


Problem Solving & Programming

Ex 6. In an academic institution, grades have to be printed for students who appeared in the final
exam. The criteria for allocating the grades against the percentage of total marks obtained are as
follows.
Marks Grade Marks Grade
91–100 O 61–70 B
81–90 E 51–60 C
71–80 A <= 50 F
The percentage of total marks obtained by each student in the final exam is to be given as input to
get a printout of the grade the student is awarded.

Solution The percentage of marks obtained by a student is represented by N. The algorithm for the
given problem is as follows.

1. START
2. PRINT“ENTER THE OBTAINED PERCENTAGE MARKS”
3. INPUT N
4. IF N > 0 AND N <= 50 THEN
PRINT “F”
5. IF N > 50 AND N <= 60 THEN
PRINT “C”
6. IF N > 60 AND N <= 70 THEN
PRINT “B”
7. IF N > 70 AND N <= 80 THEN
PRINT “A”
8. IF N > 80 AND N <= 90 THEN
PRINT “E”
9. IF N > 90 AND N <= 100 THEN
PRINT “O”
10. STOP

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 27


Problem Solving & Programming

Ex 11. Write an algorithm to print the Fibonacci series up to N terms.

Solution The Fibonacci series consisting of the following terms 1, 1, 2, 3, 5, 8, 13, … is generated
using the following algorithm.

1. START
2. PRINT “ENTER THE NUMBER OF TERMS”
3. INPUT N
4. C ←1
5. T ←1
6. T1 ←0
7. T2 ←1
8. PRINT T2
9. T ←T1 + T2
10. PRINT T
11. C ←C + 1
12. T1 ←T2
13. T2 ←T
14. IF C <= N-1 THEN GOTO 9
15. STOP

Ex 12 Write an algorithm to find the largest number among a list of numbers.


Solution The largest number can be found using the following algorithm.

1. START
2. PRINT “ENTER TOTAL COUNT OF NUMBERS IN LIST”
3. INPUT N
4. C ←0
5. PRINT “ENTER THE NUMBER”
6. INPUT A
7. C ←C + 1
8. MAX ←A
9. PRINT “ENTER THE NUMBER”
10. INPUT B
11. C ←C + 1
12. IF B > MAX THEN

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 28


Problem Solving & Programming

MAX ←B
13. IF C <= N THEN GOTO STEP 9
14. PRINT MAX
15. STOP

12. FLOWCHARTS
Definition:
A flowchart is defined as a graphical representation of an algorithm.

It is described as the sequence and flow of control information within the process. Flowchart
uses different graphical symbols to represent different activities performed at different stages
of algorithm.

Following are the symbols:


1. Flow Line Symbol
It is represented by a directional line (arrow) which indicates the flow of process and
sequence of steps in solving a given problem.

2. Start and Stop (or) Begin and End Symbol

It is represented by flat oval or egg shaped symbol. It indicates the beginning and
ending point of the flowchart. It is associated with only one incoming and outgoing
flowline.

BEGIN END

3. Input or Output Symbol


It is represented by a parallelogram.
It is used to indicate the inputs given by the user to process and the outputs given by the
process to the user.

INPUT OUTPUT

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 29


Problem Solving & Programming

4. Process Symbol

It is represented by a rectangle symbol. It is also called action symbol. It represents the


actions and calculations takes place in the process.

PROCESS

5. Connector Symbol

It is represented by a circle symbol. It is used to join the flow lines and to represent the
continuation of flow of steps when the flowchart exceeds to next page.

Connector that goes Connector that comes


to next section from previous section

6. Decision Symbol

It is represented by a rhombus or diamond shaped symbol. It is used in case of selection


algorithms.
Entry

condition

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 30


Problem Solving & Programming

Single Alternate Decision symbol

Entry

False
condition
?

True
END

Statements

Two Alternative Decision symbol

Entry

True False
condition
?

Statements - A Statements - B

Exit

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 31


Problem Solving & Programming

Multiple Alternative Decision Symbol

Entry

True
Condition - 1 Statements - 1
?

False

True
Condition - 2
Statements - 2
?

False

True
Condition - 3 Statements - 3
?

False
Statements - n

Exit
7. Loop Symbol

Entry

False
condition
?

True
END

Statements

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 32


Problem Solving & Programming

Following are the other symbols used in Flow charts.

Alternate Process Predefined Process Internal Storage

Manual Operation Card Punched Tape


Collate

Summing Junction Off-Page Connector Display


OR

Sequential Access
Sort Extract Merge
Storage

Document Direct Access Storage


Stored Data

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 33


Problem Solving & Programming

Advantages of using flowcharts

 Communication: Flowcharts are a better way of communicating the logic of a system


to all concerned.
 Effective analysis: With the help of flowcharts, problems can be analyzed more
effectively.
 Proper documentation: Program flowcharts serve as a good program documentation
needed for various purposes.
 Efficient coding: Flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
 Proper debugging: Flowcharts help in the debugging process.
 Efficient program maintenance: The maintenance of an operating program becomes
easy with the help of a flowchart.

1. Draw a flowchart to add two numbers entered by user.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 34


Problem Solving & Programming

2. Draw flowchart to find the largest among three different numbers entered by user.

3. Draw a flowchart to find the sum of the first 50 natural numbers.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 35


Problem Solving & Programming

4. Draw a flowchart for calculating the simple interest using the formula SI = (P * T * R)/100,
where P denotes the principal amount, T time, and R rate of interest. Also, show the algorithm
in step-form.

5. The XYZ Construction Company plans to give a 5% year-end bonus to each of its employees
earning Rs 5,000 or more per year, and a fixed bonus of Rs 250 to all other employees. Draw a
flowchart and write the step-form algorithm for printing the bonus of any employee.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 36


Problem Solving & Programming

6. Prepare a flowchart to read the marks of a student and classify them into different grades. If
the marks secured are greater than or equal to 90, the student is awarded Grade A; if they are
greater than or equal to 80 but less than 90, Grade B is awarded; if they are greater than or
equal to 65 but less than 80, Grade C is awarded; otherwise Grade D is awarded.

7. Draw a flowchart for printing the sum of even terms contained within the numbers 0 to 20.
Solution

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 37


Problem Solving & Programming

1.13Strategy for designing algorithms

Strategies can be devised for designing algorithms. The following is a useful strategy.

Investigation step

1. Identify the outputs needed


This includes the form in which the outputs have to be presented. Identify the input
variables available.
2. Identify the major decisions and conditions
The conditions imposed by the need identified and the limitations of the environment
in which the algorithm has to be implemented.
3. Identify the processes required to transform inputs into required outputs
This activity identifies the various types of procedures needed to manipulate the
inputs, within the bounding conditions..

Top-down development step

• Top-down development step


• Devise the overall problem solution by identifying the major components of the
system. The goal is to divide the problem solution into manageable small pieces that
can be solved separately
• Verify the feasibility of breaking up the overall problem solution. The basic idea here is
to check that though each small piece of solution procedure is independent

Stepwise refinement

• Work out each and every detail for each small piece of manageable solution procedure
• Decompose any solution procedure into further smaller pieces and iterate until the
desired level of detail is achieved.
• Group variables together which have some appropriate commonality.
• Test each small procedure for its detail and correctness and its interfacing with the
other small procedures.
• Hence, the top-down approach starts with a big and hazy goal. It breaks the big goal
into smaller components.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 38


Problem Solving & Programming

Introduction to C
C is a general-purpose programming language. It has been closely associated with the
UNIX system where it was developed, since both the system and most of the programs that
run on it are written in C. The language, however, is not tied to anyone operating system or
machine; and although it has been called a "system programming language" because it is
useful for writing compilers and operating systems, it has been used equally well to write
major programs in many different domains.

History of C Language

 C programming language was developed in 1972 by Dennis Ritchie


at AT&T (American Telephone & Telegraph) Bell laboratories,
located in U.S.A.
 Dennis Ritchie is known as the founder of C language.
 It was developed to overcome the problems of previous languages such as B, BCPL etc.
 Initially, C language was developed to be used in UNIX operating system. It inherits
many features of previous languages such as B and BCPL.
 Let's see the programming languages that were developed before C language.

Language Year Developed By

ALGOL 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 39


Problem Solving & Programming

Why Learn C?
There are a large number of programming languages in the world today—C++, Java,
Ada, BASIC, COBOL, Perl, Pascal, Smalltalk, FORTRAN, etc. Even so, there are several reasons
to learn C, some of which are stated as follows.

 C is a core language In computing, C is a general purpose, cross-platform, block


structured procedural, imperative computer programming language.
 C is a small language C has only thirty-two keywords (and only about twenty of them
are in common use). This makes it relatively easy to learn compared to bulkier
languages.
 C is quick We can write codes which run quickly, and the program can be very ‘close to
the hardware’. By that, you can access low level facilities in your computer quite easily.
 C is portable C programs written on one system can be run with little or no
modification on other systems. If modifications are necessary, they can often be made
by simply changing a few entries in a header file accompanying the main program.

Standardizations of C Language

• Both UNIX and C were created at AT&T’s Bell Laboratories in the late 1960s and early
1970s. During the 1970s the C programming language became increasingly popular.
• During the late 1970s and 1980s, versions of C were implemented for a wide variety of
mainframe computers, minicomputers, and microcomputers, including the IBM PC.
• In the early 1980s, a need was realized to standardize the definition of the C language
which in turn would help C become more widespread in commercial programming.
• In 1983 the American National Standards Institute (ANSI) formed a committee to
establish a standard specification of C known as ‘ANSI C’.
• This work ended in the creation of the so-called C89 standard in 1989. This version of
the language is often referred to as ANSI C, Standard C, or sometimes C89.
ISO/IECSO/IEC (It is a joint technical committee (JTC) of the International
Organization for Standardization (ISO) and the International Electrotechnical
Commission (IEC)).
• In 1990, the ANSI C standard (with a few minor modifications) was made by the
International Organization for Standardization (ISO) as ISO/IEC 9899:1990. This
version is sometimes called C90. Therefore, the terms ‘C89’ and ‘C90’ refer to
essentially the same language.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 40


Problem Solving & Programming

Developing Programs in C:
There are mainly three steps:
1. Writing the C program
2. Compile the program and
3. Executing it.
For these steps, there requires some software components, namely an operating system, a
text editor, and the C compiler, assembler, and linker.
• Writing or Editing the source program using a text editor or an IDE and saving it with
.c extension. Such an editor offers a complete environment for writing, developing,
modifying, testing, and debugging the programs. Such software is referred to as an
integrated development environment or IDE. An IDE is typically dedicated to a
specific programming language
• Preprocessing is the first phase of the C compilation. It processes include-files,
conditional compilation instructions and macros. The C preprocessor is used to modify
your program according to the preprocessor directives in your source code. A
preprocessor directive is a statement (such as #define) that gives the preprocessor
specific instructions on how to modify your source code
• Compilation is the second pass. It takes the output of the preprocessor, and the source
code, and generates assembler source code. The compiler examines each program
statement contained in the source program and checks it to ensure that it conforms to
the syntax and semantics of the language
• Assembly is the third stage of compilation. It takes the assembly source code and
produces an object file. After the program has been translated into an equivalent
assembly language program, the next step in the compilation process is to translate the
assembly language statements into actual machine instructions
• Linking is the final stage of compilation. After the program has been translated into
object code, it is ready to be linked. The purpose of the linking phase is to get the
program into a final form for execution on the computer
• Debugging : Removing errors from a program is called debugging. Any type of error in
your program is known as bug. During debugging an attempt is made to remove all the
known problems or bugs from the program
There are three types of errors that may occur:

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 41


Problem Solving & Programming

Compiling errors: These are given by the compiler and prevent the program from not
running.
Linking errors: These are given by the linker or at runtime and end the program. The
linker can also detect and report errors, for example, if part of the program is missing or a
non-existent library component is referenced
Runtime errors: These are given by the operating system

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 42


Problem Solving & Programming

Structure of a C program
A C program basically consists of the following sections –

Documentation Section
Header File Section or Link Section
Definition Section
Global Declaration Section
Main Section
main()
{
/* comments */
Declaration Part
Executable Part
}
User-Defined Functions Section
{
Declaration Part
Executable Part
}

Documentation Section
This section includes information about the program like Name of the program, author, date
last modified etc. This information is useful for the programmer to update source code in
future as well as to prepare documentation for software.
All these details should be defined as a “Comment”
Comment: It is a textual description about the problem, which is not a part of the program
and ignored by the compiler.
Comments in C:
Comments in C must be enclosed in following delimiters /*.................*/ called multi-line
comments.
Ex:1
/*
Author:
Date:
Description:
*/
Ex:2
/* This is
a
multi line comment */
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 43
Problem Solving & Programming

Note: We can write comments at anywhere in a program, for the sake of understanding a
program.
Header File Section or Link Section
This section is mandatory in every C program. It is used to specify which additional object
files are to be linked to our object file.
C has a vast library which contains many pre defined functions; to make use of those functions
we must include them in the source code as a header file.
This header file is included using a pre processor directive “#include”
Syntax:
#include<header file>
or
#include “header file”
Ex:
#include<stdio.h> /* To make use standard Input and Output functions */
#include<conio.h> /* To make use of console IO functions */
#include<math.h> /* To make use of mathematical functions */
Definition Section
This section is used to define macros and it is optional.
Macro: It is a named constant which substitutes its constant value wherever it appears in the
source code.
This section is included using a pre-processor directive “#define”.
Syntax:
#define MACRO value
Ex:
#define PI 3.1413
It substitutes 3.1413 wherever PI appears in the program
#define MAX 50
#define ROWS 10
#define COLS 10

Global Declaration Section


This section is used to define global variables used by any function defined in a program and it
is optional.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 44


Problem Solving & Programming

Main Section
This section is mandatory in every C program and there should be only one main function. It is
followed by the delimiters paranthesis “( )”.
The compilation and execution of a C program starts from main( ).
Syntax:
return_type main(parameter_list)
{
Declaration Part
Executable Part
}
Ex:
int main()
{
Declaration Part
Executable Part
}

User – defined Function Section


We can also define our own functions like pre defined functions are called user defined
functions

Short Answer Questions:


1. List out the advantages of High Level Languages.
2. Define a Program and Programming.
3. List out the different types of computer software.
4. Draw a figure that explains about the Compiling and Executing High-level Language
Programs.
5. Write about the role of linker and loader before the program execution.
6. Define an algorithm. Write an algorithm to find the product of three numbers.
7. Define Flow Chart. List the importance of flowchart.
8. How an Algorithm is different from Flowchart.
9. Write an algorithm and draw flowchart for finding largest among three given numbers.
10. Write the general structure of C program.
11. Write the difference between syntax error and logical error.
12. Define a comment. Write the syntax for writing comments in C.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 45


Problem Solving & Programming

Long Answer Questions:

1. What is an algorithm? Explain with suitable example.


2. Explain about the strategy for designing algorithms.
3. Explain in detail about the process of compilation and execution of a C program.
4. What is a Flow Chart? Explain different symbols used for flow chart? What is the use of
flowchart.
5. Explain the three categories of statements for Algorithm Development with examples.
6. How an Algorithm is different from Flowchart? Write an algorithm and draw flowchart
for finding largest among three given numbers.
7. With a neat diagram explain the role of the compiler in the process of developing and
testing
a high level language program.
8. Distinguish between High Level Language program and Assembly Language program.
9. Explain about the classification of Programming languages.
10. Explain about the general structure of C program, with an example.
11. What is a comment? Write the syntax for writing comments in C. What are the guidelines
to be followed while writing the comments.

************

Faculty Editors:

1. Mrs. V. Sujatha, Assistant Professor, Dept. of CSE


2. Ms. K. Sruthi, Assistant Professor, Dept. of CSE
3. Mr. K. Venkatesh, Assistant Professor, Dept. of CSE
4. Mrs. P. Rohini, Assistant Professor, Dept. of CSE
5. Dr. B. Hari Chandana, Assistant Professor, Dept. of CSE
6. Mr. C. Sudheer Kumar, Assistant Professor, Dept. of CSE

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 46

You might also like