Problem Solving & Programming Notes - Unit - I
Problem Solving & Programming Notes - Unit - I
ON
PROBLEM SOLVING
AND
PROGRAMMING
(R204GA05101)
I B.TECH I SEMESTER
Regulation: R20
(2020 – 2021)
Problem Solving & Programming
UNIT – I
Introduction to Programming, Algorithms, Flowcharts and C Programming
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
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.
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.
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
Some examples of system software are Operating System, Compilers, Interpreter, Assemblers
etc.
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.
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
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).
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.
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.
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.
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.
The steps in the process of translating a source program in a high-level language to executable
code are depicted in above Figure
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.
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.
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.
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.
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.
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.
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.
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.
‘←’ ….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
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”
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.
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
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
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
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
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
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
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.
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
INPUT OUTPUT
4. Process Symbol
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.
6. Decision Symbol
condition
Entry
False
condition
?
True
END
Statements
Entry
True False
condition
?
Statements - A Statements - B
Exit
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
Sequential Access
Sort Extract Merge
Storage
2. Draw flowchart to find the largest among three different numbers entered by user.
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.
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
Strategies can be devised for designing algorithms. The following is a useful strategy.
Investigation step
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.
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
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.
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.
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:
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
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
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
}
************
Faculty Editors: