Chapter 1
PROBLEM SOLVING: AN INTRODUCTION
Learning Objectives
After going through this chapter, you will be able to:
– Understand the basics of program writing
– Describe the goals and objectives of programming in C
– Explain the significance of input/output process sequence
– Discuss the life cycle of a program
– Understand and use logic development tools
– Explain the significance of symbols used in flowcharts
– Discuss the basic control structures used in programming
– Understand the importance of the divide and conquer method
– Explain the significance of modular programming
1.1 INTRODUCTION
In this chapter, you will learn about the basic concepts of problem solving and computer
programming. In our day-to-day life, there is a need to solve number of mathematical problems.
The simple problems, such as addition and multiplication can be solved easily but for complex
problems, such as maintaining data for a student, salary of an employee, etc., a computer is
considered more suitable. You will learn to use computers in problem solving with the help of
computer programming. Computer programming refers to the method of developing and
implementing several different sets of instructions to enable a computer to perform a certain
task. This chapter will discuss about the basic concepts of programing which include
algorithms, flowchart, basic control structures and features of a good program.
1.2 PROBLEM DEFINITION
Basically, the term computer programming refers to the method of developing and implementing
several different sets of instructions to enable a computer to perform a certain task. These
instructions of the computer programs are written using specific languages. Technically, the
computer programming is the process of writing, testing, debugging/troubleshooting and
maintaining the source code of computer programs which is exclusively written in a
2 Programming in C
programming language. A programming language is an artificial language designed to automate
the task of organizing and manipulating information, and to express problem solutions precisely.
Computer programming is, thus, a process of finding solutions to real-life problems
using computers. We need to solve a number of mathematical problems in our daily life.
Simple additions or multiplications can be solved manually. But, a computer is more suitable
to solve complex and repetitive problems easily. For example, in the case of a payroll
package, the specific Salary Payroll software calculates the gross and net pay of the
employees with the basic data provided by the user. In case of oil exploration, we write
a program to determine whether oil can be found in the given location based on collected
data. In case of railway reservation system, a number of factors have to be checked before
issuing a ticket.
Computers cannot perform magic themselves. They cannot give a solution if the problem
is not defined clearly. Defining a problem correctly is the first step in writing good programs.
After defining the problem, it is converted into computer-understandable form by a
programmer or software professional. Basically, a programmer defines the problems,
develops programs by using suitable computer languages to get the solutions.
1.3 PROBLEM SOLVING
It may be difficult to solve a complex problem as a whole at one strike. Dividing a problem
into a number of small problems makes it easy to solve complex problems, such as application
development on oil exploration, weather forecasting, satellite launching, etc. However, such
a division of the problem is possible only when the problem is already defined completely and
correctly. The problem has to be defined clearly and unambiguously, instances of which are
as follows:
Problem 1: To find out whether a triangle with given sides is a right-angled triangle:
This problem is solved on the basis of input or defined values. The user will give the input
data, i.e., the lengths of the three sides of a triangle. After issuing the input values, the
computer finds out whether a right-angled triangle can be formed with the given sides.
Problem 2: Generation of the first 10 elements of a Fibonacci series:
Here, virtually there is no input data but the program has to generate the first 10 Fibonacci
numbers. The Fibonacci numbers are defined in Mathematics. Therefore, the output should
match the definition of Fibonacci numbers. The program itself has to generate the numbers,
where the very first two values are assigned as 0 and 1. These two numbers will be creating
Fibonacci series up to given element.
Problem 3: Conversion of upper case English letters to lower case and vice versa:
Here, the input range is 26 upper or lower case alphabet; the input data is converted
into corresponding lower or upper case letters.
IS B A T
Problem Solving: An Introduction 3
In a similar manner, each program has to be analysed and a methodology found for
solving it. The programmer has to understand how to solve the problem manually before
attempting to find a computer solution to it. Then, he/she sets the algorithm to get the possible
result.
1.4 GOALS AND OBJECTIVES
Many software development projects get disorganized or faulty due to poor understanding of
the customer requirements, programming concepts and poor workmanship. The right
understanding of programming methodology is, therefore, essential for every programmer.
The programmers should attempt to keep the programs short, simple and well designed.
Program coding should be carried out in a systematic manner and has to be planned accordingly.
Therefore, program development is not merely learning the syntax of a programming language
or formulating groups of statements but creating programs that will function accurately. A
programming flowchart must be maintained by the programmer, such as what variables
should be taken, how control flow will be processed and what result should be expected as
per requirement.
The goal is to develop a program to solve a problem. The objective is to develop the
program with better quality, i.e., least number of defects, within the time schedule and budget.
Since software development is a service development and delivery; there are innumerable
possibilities for errors to creep in. The objective is, therefore, to develop a program with
minimum possible errors by understanding the requirements right from the start.
1.5 INPUT/OUTPUT PROCESS SEQUENCE
Programming is the task of developing a sequence of instructions for a computer to provide
a solution to a problem. The programmer develops the sequence of instructions or a program.
This involves the following steps:
• Defining the problem.
• Designing a solution to the given problems as an algorithm.
• Deciding the variables, looping the process, if require and analysing the expected
format of output.
• Writing the program.
• Executing the program in the computer system.
• Testing that it works correctly.
In the input/output sequence process, the input data has to be supplied at the time of
execution of the program or before, and then the computer should give the expected output.
The solution to the problem has also to be determined manually for a set of input data,
IS B A T
4 Programming in C
in order to test the correctness of the program. Therefore, problem definition has two parts,
i.e., input and output data. If these are well defined, then the problem is solved. Thus, a
computer program is considered to be an input/output process sequence.
The computer is best suited for its repetitive and correct solutions to problems. Human
beings may not always be able to give the same output for the same input. The computer
will be able to give the same output consistently irrespective of who operates the computer.
Therefore, once a program is written for solving a problem, even an ordinary user can use
it and get the results. Experts developed the word processor package but it can be used
by anybody who knows English. The developers of the word processor packages have put
in a lot of effort to ensure that an ordinary user will be able to operate the software and
get the output in whatever manner he/she desires. Even in the case of word processing
software, the inputs and outputs are clear to anybody. The input is the process of typing
a predefined set of characters in the form of sentences and the output is the desired document.
Thus, executing a computer program needs input data which leads the software to process
it as desired and display an output. Sometimes, intermediate output generated by the computer
may be taken as input for further processing and giving an output.
1.6 PROGRAM AND PROGRAM LIFE CYCLE
A computer program or software is a sequence of instructions coded in a programming
language, such as FORTRAN, Pascal, BASIC, C, C++, Java, C # (pronounced as C sharp),
etc. Software development is an engineering discipline having a set of well developed
methodologies for software development and maintenance.
1.6.1 Software Development Life Cycle (SDLC)
When programming languages became available in the 1960s, software development emerged
as an independent profession. Till then, only computer specialists who were knowledgeable
about computer hardware could make the computer perform intended operations and use
them through machine languages. The emergence of the various high-level languages and
progressive reduction of cost of computer systems gave rise to a number of software developers
or programmers. The software development projects undertaken in the early days were
essentially developing the program statements or the codes for the applications straight away.
This resulted in a software crisis, due to this the projects always getting delayed and exceeding
the original cost by two to three times or even more. The software did not perform the intended
functions on delivery and contained many defects. Therefore, a software engineering conference
was held in the early seventies to overcome the crisis. Software engineering is essentially the
application of engineering principles for the development of software. One of the
recommendations was to divide the software development activity into a number of phases.
This led to the formulation of a Software Development Life Cycle (SDLC) model. The stages
of the SDLC model are as follows:
IS B A T
Problem Solving: An Introduction 5
Planning Stage
(Resource allocation and team assignments)
Requirement Stage
(Simple description about given problem, use-case diagram)
Development Stage (Test scripts are developed and integration)
Testing Stage (Data Validation and integration is tested)
Release Stage (checklist and users-guide implementation)
1.7 STEPS IN COMPUTER PROGRAMMING
The following are the steps in computer programming:
1.7.1 Source Code
The program statement written in a high-level language, such as the C language for solving
a given problem is called the source code. The source code is typed in a text editor. Before
attempting to enter the source code, we should formulate the algorithm and document it in
pseudocode. The pseudocode is generally converted to a code in a high-level language. Then,
the same is typed in a text editor available in the system.
1.7.2 Object Code
You need to compile the source code to get the machine code that will be understood by the
CPU in the computer hardware, to execute the program. To do so, you have to compile the
source code using compiler. After compiling the program, there are two possible outcomes as
given below:
• Errors in the source code
• No errors
If there are no errors, you get an object code file, named .obj as file extension. If there
are errors, the compiler will give error messages. Therefore, the programmer should carefully
examine the program and correct all errors and recompile. When there are no errors, the
compiler will automatically generate the object code. The object code is in the machine
language. But, it is not yet ready for execution. If your program contains more than one
source code file, all the source code files will need to be compiled separately to get the
corresponding object code.
1.7.3 Linking and Loading
During this process, you combine all the object files. Another important code is the one
corresponding to the particular operating system of the computer system. This is essential for
IS B A T
6 Programming in C
executing the program in the given hardware and operating system. In order to get an executable
file for the source file, the linker will combine all these object codes. The executable file will
be in the machine code. It can now be loaded in to the system for execution by the loader.
Then, it is executed and results can be obtained.
The steps involved in program execution are as summarized below:
(a) Type the program in a text editor.
(b) Save and give a name to the program.
(c) Compile the program.
(d) Look for errors and correct them.
(e) Link the object codes to produce executable code.
(f) Load the executable code.
(g) Execute / Run the program and analyse the result.
The link editor combines the object file with library routines to produce the executable
file.
The methodology for preparation of the source code, compilation, linking and execution
may vary from system to system. One has to learn the correct operations of the Integrated
Development Environment or IDE/system being used, for the various steps given above.
1.8 LOGIC DEVELOPMENT TOOLS
The computer is instructed to solve the problem. Before writing the instructions or program
code, we use logic development tools, such as algorithms, flowcharts and pseudocode to
capture the problem accurately. Then, we write the program corresponding to each step.
Computer is a dumb machine. To make it working, you have to develop the program.
Before writing the program, you have to develop logic of each step so that simple and
complex programs can be prepared with the help of different logic development tools, such
as algorithms, flowcharts, pseudocodes, etc. To write a computer program, you have to
instruct the computer, step-by-step, exactly what you want to do, i.e., writing the program
with the help of defined algorithm and flowcharts. For this, you first develop the program
choosing a suitable language and then execute the program, following each step logically
to get the desired output. Flowcharts represent visually the flow of data through given
information. The operations performed within the system and the sequence in which they
are performed is called flowchart. It is a significant logical tool to describe the control flow
of the development of the program. Pseudocode is a kind of structured English that describes
algorithms. It allows the programmer to focus on the logic of the algorithm without being
distracted by details of language syntax.
IS B A T
Problem Solving: An Introduction 7
1.9 ALGORITHM
The methodology for problem solving using a computer is known as algorithm. An algorithm
gives a step-by-step instruction that could be converted into statements in a programming
language understandable by a computer. A simple definition of algorithm is given below:
‘A computable set of steps to achieve a desired result.’
Thus, an algorithm is a collection of steps. Each step is converted into a program
statement. The set of steps help in solving the given problem. The definition of algorithm
as per IEEE (Institute of Electrical and Electronics Engineers) standard is given below:
‘A finite set of well defined rules for the solution of a problem in a finite number of
steps’.
Thus, an algorithm is a set of precise steps. Each step indicates the operation is
performed clearly and unambiguously. The steps are narrated in a precise and simple form.
The order of operations is also important. It starts from the top and progresses sequentially
unless otherwise specified. A computer program is essentially an algorithm expressed in
a programming language. It instructs the computer to perform specific operations. Thus,
the steps in the algorithm have corresponding statements in the program.
1.9.1 History of Algorithms
A book titled Kitab al-jabr w’al-Muqabala (Rules of Reintegration and Reduction) was
written by an Iranian scientist to introduce algebra to people in the West. The word Algebra
came from al-jabr in the book title. The name of the Persian scientist who did pioneering
work is Abu Ja’far Mohammed ibn Musa-al-khwarizmi. The word algorithm evolved from
English algorism, which in turn came from Latin algorismus, derived from the name of the
Iranian scientist. It has now evolved to include all definite procedures for solving problems.
1.9.2 Documenting Algorithms
The programmer must remember that the computer cannot study the entire problem at one go
and give a solution. It is the programmer who makes the computer carry out the operations so
as to arrive at a decision. It is checked or calculated one step at a time and finally gives the
solution. Therefore, a problem requires an algorithmic or step-by-step approach for solution.
After the problem is defined, the programmer designs an algorithm giving a step-by-step
approach to solve the problem.
Algorithms are documented in a number of ways as given below:
• Natural languages
• Pseudocode
• Flowcharts
• Programming languages
IS B A T
8 Programming in C
Natural language algorithms tend to be ambiguous and lengthy. Hence, they are not
used for complex algorithms. Pseudocodes and flowcharts are structured ways to express
algorithms that avoid many of the ambiguities which may arise commonly in natural language
statements.
1.10 FLOWCHART
A flowchart is a schematic representation of an algorithm. A flowchart is used to list the
precise steps in an algorithm. It consists of geometrical shapes (boxes) of various types
connected together. It indicates the flow of control during program execution. The flow lines
have arrows to indicate the direction of flow of control between the boxes. The operation
carried out at each step is written within the box in simple English. Thus, a flowchart is a
graphical illustration of the steps involved in arriving at a solution to a problem. The flowchart
shows the sequence of steps performed and also the decision as to next step which is to be
performed.
1.10.1 Graphical Symbols used in Flowcharts
Figures 1.1(a) and (b) indicate how to depict start and end operations during program execution:
Start End
(a) (b)
Fig. 1.1 Start and End Operations
Any computational operation, such as assigning value to a variable or adding two
numbers can be depicted as given in Figure 1.2.
var1 = var2 * var3
Fig. 1.2 Computational Operation
In programming, we take a decision based on the occurrence of an event. This can be
graphically illustrated as given in Figure 1.3.
IS B A T
Problem Solving: An Introduction 9
Yes
Is
(var1= var3)?
No
Fig. 1.3 Decision Operation
Input or output is indicated by a parallelogram as given in Figure 1.4.
Fig. 1.4 Input or Output Operation
1.11 BASIC CONTROL STRUCTURES
A control structure is a block of programming that analyses variables and choose a direction
of flow control based on the given parameters. It is the basic decision-making in computing
and determine how the program will respond in certain given condition.
In programming, there are three basic control structures which are as follows:
• Simple sequence
• Selection pattern
• Repetition pattern
We will discuss them briefly as follows:
1.11.1 Simple Sequence
This is the simplest and most often used control structure. Here, the computer
executes one instruction after another in the order given in the program, as shown in Figure 1.5.
Instruction 1
Instruction 2
Fig. 1.5 Simple Sequence
IS B A T
10 Programming in C
1.11.2 Selection Pattern
In this case, the computer evaluates a condition. Then, depending on the outcome of the
evaluation, the control flows in one of the paths. Once the conditional execution is finished,
the control flows rejoin. An example is given in Figure 1.6.
A>0 False
Error
True
SQUARE A
Fig. 1.6 Selection Pattern
1.11.3 Repetition Pattern
In this case, on some condition(s) the execution of instructions loops back to a previous
instruction as given below in Figure 1.7.
Yes
Is
(n=0)?
No
GCD = m
m = n
n = m% n
Fig. 1.7 Repetition Pattern
Now, let us draw a flowchart for determining whether a triangle whose three sides are
given, is right angled or not. If the square root of the sum of the squares of any two sides
is equal to the third side, it is a right angled triangle. We have to check this by taking two
sides at a time. The flowchart is given in Figure 1.8:
IS B A T
Problem Solving: An Introduction 11
Read side1, side2, side3
x = √ side2 + side3
2
2
Yes Is
(x=side1)?
No
2
2
y = √ side1 + side3
Yes
Is
(y=side2)?
No
z = √ side1 + side2
2
2
Yes
Is
(z=side3)?
No
Write “ Right Write “ Not
Angled Triangle” Right angled"
END
Fig. 1.8 Flowchart for Checking Right Angled Triangle
IS B A T
12 Programming in C
1.12 PSEUDOCODE
This is popular tool for documenting algorithms. It is an abbreviated version of the actual
computer code and hence, it is known as pseudocode. It will look like a computer code. The
definition of Pseudocode as given in IEEE standard is given below:
‘A combination of programming language constructs and natural language used to
express a computer program design.’
A sample algorithm in a pseudocode to find out whether a triangle is right angled or
not is given below:
Algorithm – Right Angled Triangle
Step 1: Read the length of the three sides
Step 2: Store them as side1, side2 and side3
Step 3: Find the square root of (side2 square + side3 square)
Step 4: If it is equal to side1, go to Step 10
Step 5: Else, find the square root of (side1 square + side3 square)
Step 6: If it is equal to side2, go to Step 10
Step 7: Else, find the square root of (side1 square + side2 square)
Step 8: If it is equal to side3, go to Step 10
Step 9: Else, print, “The sides do not form a right angled triangle”. END
Step 10: Print, “The sides of a right angled triangle”. END
An algorithm takes care of the termination of a program. Termination of a program
is indicated by ‘End’. Programs are, in fact, the implementation of algorithms in the
programming language. Therefore, every algorithm is converted into a program.
1.12.1 Testing Algorithm
When an algorithm has been developed, it has to be tested with selected inputs. For this
purpose, one has to determine the expected output for each input. The inputs are data, which
are to be supplied for execution of a program and the output is the information or decision
conveyed by the computer. Therefore, an algorithm consists of data or inputs along with
procedure that uses the data and leads you to get a conclusion. If we look at the example of
the right angled triangle, the sides of the triangle are inputs; checking the square root of the
sum of the square of two sides with the third side is the procedure and the conclusion whether
the given triangle is a right angled triangle or not is the output. In the above problem, if we
give input as 3, 4 and 5, the output will be as per Step 10. If we give input as 4, 5 and 6, we
will get output as per Step 9. Therefore, testing is confirming that the actual output is the
same as expected. Using a pencil and a paper and noting down what happens at each step can
test algorithms.
IS B A T
Problem Solving: An Introduction 13
Some Simple Rules Governing Algorithms
The rules that govern algorithm are as follows:
• The steps in the algorithm are converted to computer instructions. Each step in the
algorithm is converted to one or more instructions in the computer language.
• The algorithmic steps must be definite not be ambiguous. It cannot contain vague
statements or inconclusive statements, such as dividing zero by zero.
• The algorithm steps should be implementable manually by a human being.
• An algorithm might receive zero or more inputs.
• The result of an algorithm is the production of one or more output. It has to deliver
an output in whatever form it may be.
• An algorithm should terminate at some point in time. It must not contain any endless
loop.
• An algorithm should be well structured with the first instruction on the top of the
program.
• It might contain alternate end points depending on some context but must definitely
end.
• An algorithm should be validated by chosen sample inputs. It should be possible
to prove that the algorithm solves the problem correctly with valid and invalid inputs.
1.12.2 Flowchart vs. Pseudocode
Flowchart
It is easy to understand and explain. Since it occupies a lot of space, it is not suitable for
larger programs. Sometimes, the designers are forced to omit steps in order to fit it in a page.
Hence, professional programmers do not prefer flowcharts.
Pseudocode
It is easy to develop and maintain. The pseudocode can be developed using C language
constructs by a C programmer. Hence, it reduces the time taken for conversion of an algorithm
to a program code later. Pseudocode occupies less space and takes less time for documenting.
But, if not properly indented and aligned while writing, it might be difficult to understand the
program logic. However, modern and professional programmers use pseudocode to document
the design of the program. Nevertheless, it is reiterated that the program development should
follow the following five steps:
(i) Defining the problem and documenting in natural language (English).
(ii) Designing a solution algorithmically and documenting the algorithm.
(iii) Writing the program.
IS B A T
14 Programming in C
(iv) Testing the program.
(v) Maintaining the program.
1.13 DIVIDE AND CONQUER
The most popular method of problem solving is to divide and conquer. This means that the
problem is divided into smaller problems, each of which must be solved to get the complete
solution. For example, if it is required to find the second smallest element in an array, the
problem could be divided into two parts, viz. arranging the elements in the array in ascending
order and then getting the second smallest element from the sorted array. This approach is
called the divide and conquer strategy.
One more example is given below to clear the concept:
If you want to find the sum of the digits in a number, it can be divided into 3 parts:
(a) Finding modulus of 10, i.e., finding the remainder when 10 divides the number.
(b) Adding the remainder to a sum whose initial value is zero.
(c) Dividing the number by 10 and then repeating the process from (a) again till
the quotient is zero.
An example will make the algorithm easy to understand. For example, if the given
number 73 is divided by 10 returns the remainder 3 and hence the sum will be, sum = 0
+ 3 = 3.
Dividing the number will give the new number = 73/10 = 7.
When the process is repeated, we will get the sum of digits = 10. Thus, the problem
has been divided into 3 sub-problems, which can be solved easily.
Now, let us look at some algorithms, which are often required for problem solving using
computers.
1.13.1 Exchanging Values of Two Variables
Suppose, you come across a need to swap values contained in two variables in many
applications, such as sorting. If you simply interchange the values, one of the values would
be lost. For example, if you want to swap values contained in var1 and var2 and if you do
as suggested below, what happens?
var1 = var2;
var2 = var1;
In the above, the contents of var2 will be transferred to var1. But, when you come
to the second statement, var2 will get the current value of var1, which is the original
value of var2. Thus, the value contained originally in var1 would be lost. To avoid this,
you need to declare another variable of the same type, say temp. Now, you can achieve
swapping in 3 steps as follows:
IS B A T
Problem Solving: An Introduction 15
temp = var1;
var1 = var2;
var2 = temp;
Here, the original value of var1 is stored in temp. Now, var2 is transferred to var1.
Thus, var1 contains the original value of var2. Then, the contents of temp, which is
nothing but the original value of var1, is transferred to var2. Thus, swapping of values
contained in two variables needs 3 steps and declaration of another variable of the same
type. The complete algorithm to swap two integer values is as follows:
Algorithm to Exchange (Swap) Values
integer var1, var2; temp;
temp ← o;
print ‘Enter two values:’;
read var1, var2;
temp ← var1;
var1 ← var2;
var2 ← temp;
print ‘The swapped values are =’;
print var1, var2;
End
Note that the above algorithm receives two inputs (read) and two outputs (print). The
algorithm terminates after writing the values, which is indicated by the End statements.
Now, try to apply the simple rules discussed in the previous section to the above algorithm
and confirm that this algorithm possesses all the characteristics of an algorithm.
You have not used any particular notation for scripting the algorithm. As you go along,
you will reduce the description part of the steps by indicating the operations to be carried
out symbolically. Therefore, there is no need to use any particular syntax for documentation
of the algorithms.
1.13.2 Decimal Base to Binary Base Conversion
The base of a number system is also called radix. While a programmer is generally comfortable
with decimal numbers, the computer system uses binary number system internally. Let us
evolve an algorithm for conversion of a decimal number to a binary number. This algorithm
deals with whole numbers only.
IS B A T
16 Programming in C
Recall how the conversion takes place with the following example:
To convert 19 into binary:
2 |19
2 |9 – 1
2 |4 – 1
2 |2 – 0
2 |1 – 0
0 – 1
The equivalent of 19 in binary is 10011.
Therefore, when you divide by 2, the first remainder is the Least Significant Bit or
LSB and the last remainder is the Most Significant Bit or MSB. For simplicity, assume
that you convert them into 8-bit numbers.
The following algorithm gives the method of converting a decimal number to an array
of bits.
Algorithm for Decimal to Binary Conversion
Step 1 : Store the decimal number in integer variable num
Step 2 : Declare an array b of size 8 to store 8 bits
Step 3 : int I = 0
Step 4 : while (I < =7)
{ b[I] = num % 2 ;
write b [I] ;
num = num/2 ;
I = I + 1 ;
}
Step 5 : END
We used a while loop in the above program. When the associated condition is satisfied,
in this case (I < = 7), the block of statements following the ‘while’ will be executed.
A block begins with an opening brace and ends with a closing brace. In this case, there
are four statements in the block.
Let us evaluate what happens in the write operation in each iteration of the while
loop.
Iteration 1 b [ 0 ] = 19 % 2 = 1
Iteration 2 b [ 1 ] = 9 % 2 = 1
Iteration 3 b [ 2 ] = 4 % 2 = 0
IS B A T
Problem Solving: An Introduction 17
Iteration 4 b [ 3 ] = 2 % 2 = 0
Iteration 5 b [ 4 ] = 1 % 2 = 1
Iteration 6 b [ 5 ] = 0 % 2 = 0
Iteration 7 b [ 6 ] = 0 % 2 = 0
Therefore, 1910 = 0010011
b [0] = LSB
b [7] = MSB
Thus, the algorithm does the conversion of a decimal number to a binary number
correctly.
1.13.3 Finding Out Greatest Common Divisor (GCD)
We will see the algorithm developed by the Greek Mathematician, Euclid for finding GCD of
two given integer values. The algorithm is given below:
Algorithm for Finding Out Greatest Common Divisor GCD (m, n)
Step 1: Read two integers m and n
Step 2: Declare temp as an integer
Step 3: while n! = 0
{ temp = m % n;
m = n;
n = temp;
}
Step 4: Write GCD = m;
Step 5: End
It is the convention in C language to use ‘= =’ to check whether a is equal to b. We
use ! = to check whether a is not equal to b.
Let us see how it works with an example.
First Iteration
Let m = 44 and n = 6
We want to find out GCD (44, 6)
Since n is not equal to 0 in the Step 3, we go to the while block.
The following operations take place:
temp = 44 % 6 = 2
m = n \ m = 6 now
n = temp \ n = 2 now.
Now we go to Step 3 again.
IS B A T
18 Programming in C
Second Iteration
Since n is not equal to zero, we go to the while block again.
temp = 6%2 = 0
m = n\m = 2
n = temp = 0
Now we go to Step 3
Since n = 0, we go to Step 4
We write GCD = m = 2
Then, the execution stops.
The above algorithm can be written in a much simpler manner using recursive functions.
Since it is too early to discuss about recursion, the algorithm has been implemented as above
and works correctly.
1.13.4 Generation of Fibonacci Sequence
There are a number of sequences in Mathematics and Fibonacci is one such sequence. Its
first element is 0 and the second is 1. Thereafter, the next element is the sum of the previous
two numbers. For example:
fib[0] = 0
fib[1] = 1
fib[2] = fib[1] + fib[0] = 1+0 = 1
fib[3] = fib[2] + fib[1] = 1+1 = 2
fib[4] = fib[3] + fib[2] = 2+1 = 3
fib[5] = fib[4] + fib[3] = 3+2 = 5
Therefore, if the total number of elements in the series is given, the series can be
computed. The algorithm is simple.
Algorithm Fibonacci Sequence
Step 1: fib[0] = 0, fib[1] = 1, int i = 2, int array fib[20]
Step 2: print fib[0] and fib[1]
Step 3: while (i<20)
{
fib[i] = fib[i-1] + fib[i-2]
print fib[i]
i ++ ;
}
IS B A T
Problem Solving: An Introduction 19
This program will calculate 20 Fibonacci numbers. This is achieved by the while
loop.
In the above algorithm, we declare an array fib[20]. This means the size of the
array is 20. It is the convention in C and languages derived from it to denote the first element
of the array with subscript 0 like fib[0] and in this 20 element array, the last element
is fib[19]. Let us verify whether the algorithm works correctly.
fib[2] = fib[2-1] + fib[2-2]
= fib[1] + fib[0]
=1 + 0 = 1
Similarly, fib[3] = fib[2] + fib[1]
= 1 + 1 = 2
Thus, the algorithm works correctly.
1.14 MODULAR PROGRAMMING
Modular programming is a good programming concept. Instead of writing one large program,
it is better to divide it into a number of sub-tasks and code each one of them separately. Here,
each function is coded as a separate module. This modularization has many advantages. One of
them being the modules can be reused in other programs. The modules are tested individually
and later integrated with other modules.
The use of iteration constructs, such as for, while, etc., is encouraged in modular
programming. The module is designed in such a manner that it has one entry point and
one exit point. Modular programming is a prerequisite not only for structured programming
but also for object-oriented programming.
1.14.1 Structured Programming Concept
Two mathematicians Corrado Bohm and Giuseppe Jacopini proved that any computer program
could be written only with three program structures as:
• Sequences
• Decisions
• Loops
This discovery is considered to be a precursor methodology for modern programming
known as structured programming. Prof. Edsger W. Dijkstra suggested that the goto
statement should be abolished from all high-level languages because of its ill effects on
programs. The programs that include goto statements can cause innumerable problems,
particularly during maintenance of the software. The program, which uses goto statement,
is called spaghetti code – code that has no simple direct logical structure.
Structured programming is a preferred methodology for programming in procedure-
oriented languages. Structured programming consists of guidelines for designing programs.
Structured programming concepts were evolved to improve the quality of programs.
IS B A T
20 Programming in C
1.14.2 Features of Structured Programming
It is a philosophy of a concept that facilitates design of programs. They are easily
understandable and easily modifiable. Some of the features of structured programming are
given below.
• Flow of control in the program should be as simple as possible.
• The program should be constructed using independent modules or functions or sub
routines.
• It uses only three types of logical structures as given below:
o Sequences: Statements that are executed one after another.
o Decision: One of the two blocks of a program code is executed based on the
outcome of testing a particular condition. Example is ‘if...else’ structure.
o Loops or Iteration: One or more statements are executed repeatedly as long
as a particular condition or a combination of conditions remains true.
1.14.3 Object Oriented Programming
High-level programming languages, such as FORTRAN, Pascal, BASIC, C and COBOL
are known as function-oriented or procedure-oriented languages. They have been used for
developing important and mission critical applications. In these languages, computer programs
are organized as a sequence of instructions. In function-oriented programming, the emphasis
is on procedures or instructions and data integrity does not get due importance. In large
software projects, a number of programmers will be involved in programming. Each one will
develop programs for some portion of the product. An inexperienced programmer might
spoil the integrity of some data items inadvertently due to poor understanding. This is due to
the inherent design of the function-oriented programming languages where data and function
are not tied to each other closely. They are independent of each other causing major problems
while the software is put to use.
The principle of Object Oriented Programming (OOP) is to combine both data and the
associated functions into a single unit called a class. An object in programming means data.
Data is, therefore, predominant in object oriented programming. However, in the object
oriented paradigm, accessibility of data is restricted and therefore, accidental corruption
of data is minimized or eliminated. Thus, OOP ensures integrity of data. C++, Java, C #,
etc., are some languages which facilitate OOP.
In both programming paradigms namely; structured programming using procedure
oriented languages and object oriented programming, the following two approaches are
possible:
• Top-down approach
• Bottom-up approach
IS B A T
Problem Solving: An Introduction 21
Top-Down Approach
The program is constructed and frequently designed using top-down design methodology.
The top-down design model involves designing the overall program structure first,
followed by designing individual functions.
Bottom-Up Approach
The opposite of top-down methodology is bottom-up methodology, wherein individual functions
are designed first and finally the structure of the program is made.
Top-Down Structured Design
One of the earliest methodologies for software analysis and design is top-down structured
design. This is the method promoted by the early high-level languages, such as FORTRAN
and COBOL. C programs are also developed using top-down structured design. In a C program,
the main() function is at the top of the program structure. It calls other functions. Hence,
a C program is represented in the form of a tree, with a single node at the top, which calls a
number of other nodes. The nodes may in turn call some other nodes, and so on. This
methodology is called top-down structured design. In this methodology, we divide and conquer
by partitioning the functions to be implemented.
1.14.4 Advantages of Structured Programming
Structured programming also means that we develop an understandable and maintainable
program. Many high level languages, such as Applied Decision Analysis (ADA), Pascal, C,
FORTRAN, etc., support structured programming.
The primary purpose of structured programming is to create the right procedures that
enable the design of a program to be correct, understandable, testable and modifiable.
Structured programming results in additional advantages as follows:
Since top-down structured design is advocated during the high-level design of the
program, a number of modules would have been identified with clear specifications.
Therefore, a number of programmers work in parallel, designing one module. Furthermore,
the programmer understands the role of each of the modules in the overall program structure
since he starts from the top-level design document very early in the project.
It has also been found that structured programming reduces the time to develop
programs, because of work parallelism as explained above as well as clarity in the complete
structure of the program. Furthermore, structured programming facilitates divide and conquer
technique for the solution of the problem. This, thereby helps in focussing on one problem
at a time, that too smaller problems. All these lead to quick turn-around time for development
of programs.
IS B A T
22 Programming in C
1.15 WRITING GOOD COMPUTER PROGRAMS
We have to develop an understandable and maintainable program. Some of the guidelines of
good programming practices are as follows:
• Write only one statement per line.
• Coin meaningful names for constants, variables and functions.
• Use capitals for names of constants.
• Divide programs into functions or classes as the case may be.
• Each function and class defines one task.
• Each function and class must have at least one comment statement.
• Skip a line between functions and classes.
• Skip a line after declaration statements in the main()function as well as each function.
• Bring clarity by skipping lines wherever required.
• Put only one brace on each line.
• Align all opening braces and closing braces.
• Indent as much as possible to bring out logical structure of the program.
• Some of the program statements that could be indented are body of function, class,
body of loop, body of if..else statements.
• Indent each case in switch statement.
• Indent an item within a struct/class declaration.
1.15.1 Features of a Good Computer Program
The features of a good program are as follows:
(a) Efficiency: There are two aspects which are considered to estimate the efficiency of
computer software as given below:
• Response time or speed of execution.
• Main memory consumed to execute the program.
A program is efficient if its speed of execution is faster and at the same time it consumes
lesser memory.
(b) Correctness or Integrity: This is a measure of accuracy of the results produced when
executing the program.
(c) Degree of Structured Programming: This attribute measures to produce programs
with clear flow and design along with hierarchical structure.
(d) Degree of Modularity: It enables multiple programmers to divide the work and debug
pieces of the program independently.
IS B A T
Problem Solving: An Introduction 23
(e) Simplicity: This attribute measures the ease with which the program can be understood.
(f) Maintainability: This is a measure of ease of modifications of the program.
The time taken to locate the module that contains error will be much shorter in modular
structured programs. Since the functions are cohesive and there is lesser coupling
between functions, the side effects of maintenance will also be minimal.
(g) Reusability: Reusability is facilitated by the modular design of the program. Each
module is a good candidate for reusability in different programming projects.
(h) Ease of Debugging: Small codes are easy to debug rather than large programs. The
wrong understanding of the specifications of each module, will be avoided while
developing and testing the program. Therefore, modular programming enhances ease
of debugging.
(i) Enhanced Understandability: Structured programming advocates adequate comment
statements and documentation. It also advocates defining meaningful names for the
functions as well as variables and constants. All these facilitate ease of understanding
of the complete program.
KEY TERMS
• Computer programming: The process of finding solutions to real life problems using
computers.
• Algorithm: A step by step instruction that could be converted into statements in a
programming language understandable by a computer.
• Flowchart: A graphical illustration of the steps involved in arriving at a computer
solution to a problem.
• Pseudocode: It is an abbreviated version of the actual computer code.
QUESTIONS AND EXERCISES
Short-Answer Questions
1. How is a computer problem solved?
2. What are programming goals and objectives?
3. What do you mean by input and output processes?
4. Define the term coding and testing.
5. State the difference between linking and loading.
6. What do you understand by pseudocode?
7. Write the important guidelines of an algorithm.
8. Why is the divide and conquer method used?
IS B A T
24 Programming in C
Long-Answer Questions
1. Explain the features and importance of program life cycle with the help of a diagram.
2. Discuss the types of errors encountered in a program with the help of an example.
3. Write the steps involved in computer programming.
4. What are algorithms? Write an algorithm to find the area of a square.
5. Explain the basic control structures used in programming with the help of an example.
6. Differentiate between structured programming and object oriented programming with
relevant examples.
7. Explain the features of good programming. Write a sample C program.
IS B A T