Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Chapter -2: Problem Solving using Computer

What is a problem?
Problem is defined as the difference between an existing situation and a desired
Situation, that is, in accordance with calculation; a problem is numerical situation and has
complex form. Solution is desired situation and has simplest form. If a problem is solved by
computing using machine called computer, then such process is called Problem Solving using
Computer. The activities we have to plan in a sequence so that we can solve the problems and
get fruitful outcomes are:

1. Problem Analysis.
2. Algorithm development.
3. Flowchart development
4. Coding.
5. Compilation and Execution.
6. Debugging and Testing.
7. Documentation.

2.1 Problem Analysis


If you have studied a problem statement, then you must analyze the problem and determine how
to solve it. First, you should know the type of problem that is, nature of problem. In
programming point of view, the problem must be computing. At first you try to solve manually.
If it is solvable manually by using your idea and knowledge, then you can use such idea and
principle in programming and solve the problem by using computer. So, you must have well
knowledge about a problem. In order to get exact solution, you must analyze the problem. To
analyze means you should try to know the steps that lead you to have an exact solution.
Problem analysis should clearly specify the following tasks.
 Objectives
The problem should be stated clearly so that there will not be the chance of having right
solution to the wrong problem. Simple problem can be stated early but complex problem
may need a complex analysis with careful coordination of people, procedure and
programs.
 Output Requirements
Wisely study what should be the output of the system being developed. Programmer or
system analyst may design the output but best person to design output is end user. So it is
better to design output of system sitting with end user
 Input Requirements
To get above designed output, it is required to define the input data and source of input
data.
 Processing Requirement
It is required to clearly define processing requirements to convert the given input data to
required output.
 Evaluating Feasibility
It is one of the important phases where we mainly decide whether the proposed software
development task is technically and economically feasible.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


2.2 Algorithm Development & Flowcharting
An algorithm is step by step description of activities or methods to be processed for getting
desired output from a given input. OR
An algorithm is the step by step description of the procedure written in human understandable
language for solving given problems.
Example
1. Write an algorithm to find area of a circle of radius r.
Inputs to the algorithm: radius of circle
Expected output: area of circle
Algorithm
Step1: Start
Step2: Declare necessary variables Area, r, PI
Step3: Read/Input radius r of circle
Step4: Area=PI*r*r //Calculation of area
Step5: print Area
Step6: End
2. Write an algorithm to find largest among given three numbers?
Algorithm
Step1: Start
Step2: Declare variables a, b and c
Step3: Read variables a, b and c
Step4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else If b>c
Display b is the largest number.
Else
Display c is the largest number.
step: End
Type of Algorithms
The algorithm and flowchart, classification to the three types of control
structures. They are:
1. Sequence
2. Branching (Selection)
3. Loop (Repetition)
These three control structures are sufficient for all purposes.
 The sequence is exemplified by sequence of statements place one after the other – the one
above or before another gets executed first. In flowcharts, sequence of statements is
usually contained in the rectangular process box.
 The branch refers to a binary decision based on some condition. If the condition is true,
one of the two branches is explored; if the condition is false, the other alternative is taken.
This is usually represented by the ‘if-then’ construct in pseudo-codes and programs. In
flowcharts, this is represented by the diamond-shaped decision box. This structure is also
known as the selection structure.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


 The loop allows a statement or a sequence of statements to be repeatedly executed based
on some loop condition. It is represented by the ‘while’ and ‘for’ constructs in most
programming languages, for unbounded loops and bounded loops respectively.
(Unbounded loops refer to those whose number of iterations depends on the eventuality
that the termination condition is satisfied; bounded loops refer to those whose number of
iterations is known before-hand.) In the flowcharts, a back arrow hints the presence of a
loop. A trip around the loop is known as iteration. You must ensure that the condition for
the termination of the looping must be satisfied after some finite number of iterations,
otherwise it ends up as an infinite loop, a common mistake made by inexperienced
programmers. The loop is also known as the repetition structure.

Properties
Finiteness: Program should have finite number of steps to solve a problem.
Definiteness: The action of each step should be defined clearly without any ambiguity.
Inputs: Inputs of the algorithms should be defined precisely, which can be given initially or
while the algorithm runs.
Outputs: Each algorithm must result in one or more outputs.
Effectiveness: It should be more effective among the different ways of solving the problems.

Guidelines for writing algorithm


 Use plain language. In any example, english language is used.
 Do not use any programming language specific syntax.
 Every job to be done should be described clearly without any assumptions.
 The developed algorithm must have a single entry and exit point.

Flowchart
A flowchart is a pictorial representation of an algorithm that uses boxes of different shapes to
denote different types of instructions. The actual instructions are written within these boxes using
clear and concise statements. These boxes are connected by solid lines having arrow marks to
indicate the flow of operation, that is, the exact sequence in which the instructions are to be
executed.
Advantages of Using Flowcharts
 Communication: Flowcharts are better way of communicating the logic of a system to
all concerned or involved.
 Effective analysis: With the help of flowchart, problem can be analyzed in more
effective way therefore reducing cost and wastage of time.
 Proper documentation: Program flowcharts serve as a good program documentation,
which is needed for various purposes, making things more efficient.
 Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
 Proper Debugging: The flowchart helps in debugging process.
 Efficient Program Maintenance: The maintenance of operating program becomes easy
with the help of flowchart. It helps the programmer to put efforts more efficiently on that
part

Compiled By: Deepak Kr. Singh, Pradeep Khanal


Disadvantages of Using Flowcharts:
 Complex logic: Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy. This will become a pain for the user, resulting
in a waste of time and money trying to correct the problem.
 Alterations and Modifications: If alterations are required the flowchart may require re-
drawing completely. This will usually waste valuable time.
 Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.

Flowchart Symbols

Guidelines to be followed to draw a flowchart

 In drawing a proper flow chart, all necessary requirements should be listed out in
logical order.
 The flowchart should be clear, neat and easy to follow. There should not be any
room for ambiguity in understanding the flow chart.
 The usual direction of the flow of a procedure or system is from left to right
or top to bottom.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


 Only one flow line should come out from a process symbol.
 Only one flow line should enter a decision symbol, but two or three flow lines, one
for each possible answer, should leave the decision symbol.
 Only one flow line is used in conjunction with terminal symbol.
 W ri t e wi thin st andard fl ow chart s ym bols bri efl y. As necessar y, you can
us e t he annotation symbol to describe data or computational steps more clearly.
 If the flowchart becomes complex, it is better to use connector symbols
to reduce the number of flow lines. Avoid the intersection of flow lines if you
want to make it more effective and better way of communication.
 Ensure that the flowchart has a logical start and finish.
 It is useful to test the validity of the flowchart by passing through it with a simple
test data

(Before coding analysis and design is important. Here explain importance of problem analysis,
algorithm and flowcharting.)

Coding

In order to make a program in any programming language, what we have written is known as
code. The act of writing code in a computer language is known as coding. In other words, code is
a set of instruction that a computer can understand.

Compilation & Execution

The process by which source codes of a computer (programming) language are translated into
machine codes is known as compilation. After compilation if everything is ok, the code is going
under other process that is known as execution. We can get the required output after execution
process.

Compiler:
A compiler is a program that translates a program written in High level language to executable
machine language. The process of transferring High level source program in to object code is a
lengthy and complex process as compared to assembling. Compliers have diagnostic capabilities
and prompt the programmer with appropriate error message while compiling a High level
language program. The corrections are to be incorporated in the program, whenever needed, and
the program has to be recompiled. The process is repeated until the program is mistake free and
translated to an object code. Thus the job of a complier includes the following:
 To translate High level language source program to machine codes.
 To trace variables in the program.
 To include linkage for subroutines.
 To allocate memory for storage of program and variables.
 To generate error messages, if there are errors in the program.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


Compilation Process

Source Source Source

Compiler

Object Object Object


file File File

Executable
Runtime Linker program
Library

Figure: Illustration of compilation process

The process of translation from high level language (source code) to low level language (object
code) is called compilation.

 The first step is to pass the source code through a compiler, which translates the high
level language instructions into object code.
 The final step is producing an executable program is to pass the object code through a
linker. The linker combines modules and gives real values to all symbolic addresses,
there by producing machine code.
 Compilation process ends producing an executable program.
 The compiler stores the object and executable files in secondary storage.
 If there is any illegal instruction in the source code, compiler lists all the errors during
compilation.

Interpreter

The basic purpose of interpreter is same as that of complier. In compiler, the program is
translated completely and directly executable version is generated. Whereas interpreter translates
each instruction, executes it and then the next instruction is translated and this goes on until end
of the program. In this case, object code is not stored and reused. Every time the program is
executed, the interpreter translates each instruction freshly. It also has program diagnostic
capabilities. However, it has some disadvantages as below:
 Instructions repeated in program must be translated each time they are executed.
 Because the source program is translated fresh every time it is used, it is slow process or
execution takes more time. Approx. 20 times slower than complier.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


Interpretation means the process by which high level language is translated into machine level
language by interpreter and program is translated and executed line by line.

Assembler:
Assembler is a computer program which is used to translate program written in Assembly Language
in to machine language. The translated program is called as object program. Assembler checks each
instruction for its correctness and generates diagnostic messages, if there are mistakes in the
program. Various steps of assembling are:
 Input source program in Assembly Language through an input device.
 Use Assembler to produce object program in machine language.
 Execute the program.
Difference between compiler and Interpreter:

Difference between compiler and assembler:

COMPILER ASSEMBLER
Generates the assembly language code or Generates the relocatable machine code.
directly the executable code.
Preprocessed source code. Assembly language code.
The compilation phases are lexical analyzer, Assembler makes two passes over the given
syntax analyzer, semantic analyzer, input.
intermediate code generation, code
optimization, code generation.
The assembly code generated by the compiler The relocatable machine code generated by an
is a mnemonic version of machine code. assembler is represented by binary code.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


2.4 Debugging and Testing
It is the process of detecting and removing errors in a program, so that the program produces the
desired results on all occasions. Before going in details about debugging and testing process,
different errors that can occur should be discussed.

Errors
While writing C programs, errors also known as bugs in the world of programming may occur
unwillingly which may prevent the program to compile and run correctly as per the expectations
of the programmer.
Basically 4 different types:

1. Runtime Errors
Runtime errors are those errors that occur during the execution of a c program and generally
occur due to some illegal operations that performed in the program.
Examples of some illegal operations that may produce runtime errors are:

 Dividing a number by zero.


 Trying to open a file which is not created.
 Lack of free memory space.
It should be noted that occurrence of these errors may stop program execution, thus to encounter
this, a program should be written such that it is able to handle such unexpected errors and rather
than terminating unexpectedly, it should be able to continue operating. This ability of the
program is known as robustness and the code used to make a program robust is known as guard
code as it guards program from terminating abruptly due to occurrence of execution errors.

2. Compile Errors
Compile errors are those errors that occur at the time of compilation of the program. C compile
errors may be further classified as:

 Syntax Error
When the rules of the c programming languages are not followed, the compiler will show
syntax errors.
For example, consider the statements,
int a,b:
The above statement will produce syntax error as the statement is terminated with :
rather;

 Semantic Errors
Semantic errors are reported by the compiler when the statements written in the c
program are not meaningful to the compiler.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


For example, consider the statement,
b+c=a;
In the above statement, we are trying to assign value of a in the value obtained by
summation of b and c which has no meaning in c. the correct statement will be
a=b+c;
3. Logical Errors

Logical errors are the errors in the output of the program. The presence of logical errors leads to
undesired or incorrect output and are caused due to error in the logic applied in the program to
produce the desired output.
Also, logical errors could not be detected by the compiler, and thus, programmers has to check
the entire coding of a c program line by line.

4. Latent Errors

The hidden errors that shows up only when a particular set of data is used.
Example: r=(x+y)/(p-q)
This expression shows up error when p=q.

Debugging

It is the process of isolating and correcting different type of errors. Different debugging
techniques are given below.

1. Error Isolation

 It is used for locating an error resulting in a diagnostic message.


 We can generally find the location of errors by temporarily deleting a certain portions of
program code and rerunning the program to see whether the error is again appeared or
not.
 If error is not appeared then , deleted portion of programs has error. And if error again
appears then that deleted portion is error free.
 Here in this process, temporary deletion is done by commenting those portion of
program.

2. Tracing

 In this technique, printf() statement is used to print the values of some important
variables at different stages of program.
 If any value is incorrect, we can easily fix the location of the error.

3. Watch Values
 A watch value is the value of variable or an expression, which is displayed continuously
as the program executes.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


 Thus we can see the changes in a watch value as they occur, in response to the program
logic.
 By inspecting these values carefully, we can determine where the program begins to
generate an incorrect or unexpected value.

4. Breakpoints

 It is a temporary stopping point with in a program.


 Each breakpoint is associated with a particular instruction within the program.
 When the program is executed, the program execution will temporarily stop at the
breakpoint before the instruction is executed.
 Execution may be resumed until next breakpoint is encountered.
 Breakpoints are often used in conjunction with watch values.
Debug Add Breakpoints provide the requested information in the dialog box.
Or
Select a particular line within the program press function F5.
To disable the breakpoint again press function key F5.
5. Stepping
 The process of executing one instruction at a time is called execution.
 We can determine which instruction produce erroneous result or generate error message
by stepping through the entire program.
 Stepping is often used with watch values, allowing us to trace the entire history of a
program as it executes.

Testing
It is the process of executing a program or system with the intent of finding errors. It involves
any activity aimed at evaluating an attribute or capability of a program or system and
determining that it meets its required results. Testing is usually performed for the following
purposes:

 To improve quality.
 For verification and validation.
 For reliability estimation.
Testing process may include the following two stages:

Human Testing

 It is an effective error detection process and is done before the computer based testing
begins.
 It includes code inspection by the programmer and test group and review by a peer group.
 The test is carried out statement by statement and is analyzed with respect to checklist of
common programming errors.
 In addition to finding the errors, the programming style and choice of algorithm are also
reviewed.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


Computer Based Testing

 It involves two stages namely compile testing and run time testing.
 Compile testing can show different syntax errors and run time errors may produce the run
time error message such as null pointer assignment and stack overflow.
 After removing errors, it is required to run the program with test data to check whether
the program is producing the correct result or not.
 Program testing can be done either at module (function) level i.e. unit testing or program
level .
 An integration testing is done to find the errors associated with interfacing.

Difference between Testing and Debugging

Testing Debugging
The purpose of debugging is to correct those bugs
The purpose of testing is to find bugs and errors. found during testing.

Testing is done by tester. Debugging is done by programmer or developer.


It can be automated. It can’t be automated.

It can be done by outsider like client. It must be done only by insider i.e. programmer.
Most of the testing can be done without design Debugging can’t be done without proper design
knowledge. knowledge.

2.5 Program Documentation


Program Documentation refers to the details that describe a program. While writing programs, it
is good programming practice to make a brief explanatory note on the programmer program
segment. This explanatory note is called comment. It explains how the program works and
interact with it. Thus, it helps other programmers to understand the program. Program
documentation is used for both the original programmer and beginner. The final document
should contain the following information:

 A program analysis document with objectives, inputs, outputs and processing procedures.
 Program design document algorithm and detailed flowchart and other appropriate
diagram.
 Program verification documents, with details of checking, testing and correction
procedures along with the list of test data.
 Log is used to document future program revision and maintenance activity.

Compiled By: Deepak Kr. Singh, Pradeep Khanal


Examples:

Write an algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Write an algorithm to find all roots of a quadratic equation ax2+bx+c=0.


Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant
D←b2-4ac
Step 4: If D≥0
r1←(-b+√D)/2a
r2←(-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp←b/2a
ip←√(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop

Write an algorithm to find the factorial of a number entered by user.


Step 1: Start
Step 2: Declare variables n,factorial and i.
Step 3: Initialize variables
factorial←1
i←1
Step 4: Read value of n
Step 5: Repeat the steps until i=n
5.1: factorial←factorial*i
5.2: i←i+1
Step 6: Display factorial
Step 7: Stop

Compiled By: Deepak Kr. Singh, Pradeep Khanal


Write an algorithm to check whether a number entered by user is prime or not.
Step 1: Start
Step 2: Declare variables n, i, flag.
Step 3: Initialize variables
flag←1
i←2
Step 4: Read n from user.
Step 5: Repeat the steps until i<(n/2)
5.1 If remainder of n÷i equals 0
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
Display n is not prime
else
Display n is prime
Step 7: Stop

Q6.Write an algorithm to find the Fibonacci series till term≤1000.


Step 1: Start
Step 2: Declare variables first_term,second_term and temp.
Step 3: Initialize variables first_term←0 second_term←1
Step 4: Display first_term and second_term
Step 5: Repeat the steps until second_term≤1000
5.1: temp←second_term
5.2: second_term←second_term+first term
5.3: first_term←temp
5.4: Display second_term
Step 6: Stop

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

Compiled By: Deepak Kr. Singh, Pradeep Khanal


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

Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0.

Draw a flowchart to find the Fibonacci series till term≤1000.

Compiled By: Deepak Kr. Singh, Pradeep Khanal

You might also like