0% found this document useful (0 votes)
60 views70 pages

CSC1302 - Lectuer Notes

The document discusses an introduction to problem solving in computer science. It covers analyzing problems, developing algorithms, coding solutions, and testing programs. Key aspects include breaking problems into smaller subtasks, defining precise steps in algorithms, and using various programming languages and testing methods.

Uploaded by

khalidnuruddin8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views70 pages

CSC1302 - Lectuer Notes

The document discusses an introduction to problem solving in computer science. It covers analyzing problems, developing algorithms, coding solutions, and testing programs. Key aspects include breaking problems into smaller subtasks, defining precise steps in algorithms, and using various programming languages and testing methods.

Uploaded by

khalidnuruddin8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

CSC 1302: INTRODUCTION TO PROBLEM SOLVING

COURSE TUTOR:
BASHIR ABDU MUZAKKARI, Ph.D.

DEPARTMENT OF COMPUTER SCIENCE


YUSUF MAITAMA SULE UNIVERSITY, KANO
DISCLAIMER

This document does not claim any originality and cannot be used as
substitute for prescribed textbooks. The information presented here is
purely a collection by the course lecturer for teaching assignments.
Various textbooks as well as freely available materials from the internet
were consulted for preparing this document. The ownership of the
information lies with the respective authors or institutions.
Introduction to Problem Solving

“Computer Science is a science of abstraction - creating the right model for a


problem and devising the appropriate mechanizable techniques to solve it.”

–A. Aho and J. Ullman


Introduction to Problem Solving
CHAPTER 1: Introduction to Problem Solving
Introduction to Problem Solving
 We use computers daily to do various tasks in a faster and more accurate
manner.

 For example, using a computer or smartphone, we can book train, airline,


cinema and bus tickets online.

 In developed countries with enormous railway network, train reservation is


a complex task.

 Making reservation involves gathering information about many aspects,


such as details of trains (type, compartment, schedule, etc.), simultaneous
booking of tickets by multiple users and many other related factors.
Introduction to Problem Solving
 The use of computers has ease the booking of train tickets. Online booking
of tickets has added to our comfort by enabling us to book tickets from
anywhere, anytime.

 We usually use the term computerization to indicate the use of computer to


develop software in order to automate any routine human task efficiently.

 Computers are used for solving various day-to-day problems and thus
problem solving is an essential skill that a computer science student should
know.

 It is pertinent to mention that computers themselves cannot solve a


problem.
Introduction to Problem Solving
 Precise step-by-step instructions should be given by us to solve the problem.

 Thus, the success of a computer in solving a problem depends on how


correctly and precisely we define the problem, design a solution (algorithm)
and implement the solution (program) using a programming language.

 Thus, problem solving is the process of identifying a problem, developing an


algorithm for the identified problem and finally implementing the algorithm
to develop a computer program.
CHAPTER 2: Steps for Problem Solving
Steps for Problem Solving

1. Analyzing the Problem

2. Developing an Algorithm

3. Coding

4. Testing and Debugging


Steps for Problem Solving

1. Analyzing the Problem


 It is important to clearly understand a problem before we
begin to find the solution for it.

 If we are not clear as to what is to be solved, we may end up


developing a program which may not solve our purpose.

 Thus, we need to read and analyze the problem statement


carefully in order to list the principal components of the
problem and decide the core functionalities that our
solution should have.

 By analyzing a problem, we would be able to figure out what


are the inputs that our program should accept and the
outputs that it should produce.
Steps for Problem Solving

2. Developing an Algorithm
 It is essential to device a solution before writing a program
code for a given problem. The solution is represented in
natural language and is called an algorithm.

 We can imagine an algorithm like a very well-written recipe


for a dish, with clearly defined steps that, if followed, one
will end up preparing the dish.

 We start with a tentative solution plan and keep on refining


the algorithm until the algorithm is able to capture all the
aspects of the desired solution.

 For a given problem, more than one algorithm is possible


and we have to select the most suitable solution.
Steps for Problem Solving

3. Coding
 After finalizing the algorithm, we need to convert the
algorithm into the format which can be understood by the
computer to generate the desired solution.

 Different high level programming languages can be used for


writing a program.

 It is equally important to record the details of the coding


procedures followed and document the solution. This is
helpful when revisiting the programs at a later stage.
Steps for Problem Solving

4. Testing and Debugging


 The program created should be tested on various
parameters to ensure conformity with the user
requirements by generating correct output for all possible
inputs.

 In the presence of syntactical errors, no output will be


obtained. In case the output generated is incorrect, then the
program should be checked for logical errors, if any.
 Software industry follows standardized testing methods like
unit or component testing, integration testing, system
testing, and acceptance testing while developing complex
applications.
 Testing is carried out to ensure that the software meets all
the business and technical requirements and works as
expected.
CHAPTER 3: Algorithm
Algorithm
 In our day-to-day life we perform activities by
following certain sequence of steps.

 Examples of activities include getting ready for


school, making breakfast, riding a bicycle, and so
on.

 To complete each activity, we follow a sequence of


steps.
Algorithm
 An algorithm specifies a series of steps that perform a particular
computation or task.

 Algorithms were originally born as part of mathematics – the word


“algorithm” comes from the Arabic writer Muḥammad ibn Mūsā al-
Khwārizmī, (c. 850 AD) as the Latin translation of AlKhwarizmi was called
‘Algorithmi’.

 Algorithms resemble recipes. Recipes tell you how to accomplish a task by


performing a number of steps. For example, to bake a cake the steps are:
preheat the oven; mix flour, sugar, and eggs thoroughly; pour into a baking
pan; and so forth.
Concepts of Algorithm
 Problem Solving involves the abstraction and decomposition of large
amount o problem into smaller manageable subtasks that can be handled
independently.

 An algorithm is vital in the planning and execution of solutions to the


problem. It specifies the sequence of steps needed to achieve the overall
result.

 More than one algorithm can be written for a particular problem, but the
choice of selecting a particular algorithm above others depends on the
following factors: reliability, accuracy, ease of modification, and execution
time when converted to a high-level language.
Components of Algorithm
 Most of the algorithms used in solving program related problems consist of
three major sections: the input, processing and output.

 To execute a task the algorithm requires some data (i.e. input), it performs
some computation on the data (i.e. processing) then it produces result (i.e.
output). The processing comprises of either, computation, selection,
iteration, etc. or all of them.
Characteristics of a Good Algorithm
 Precision — the steps are precisely stated or defined.

 Uniqueness — results of each step are uniquely defined and only depend
on the input and the result of the preceding steps.

 Finiteness — the algorithm always stops after a finite number of steps.

 Input — the algorithm receives some input.

 Output — the algorithm produces some output.


Roles of Algorithm in Problem Solving
 Algorithm helps in the evaluation of a problem to know if it can be solved
using a computer. Once an algorithm can be written for a problem then the
problem can be solved using computational means.

 Algorithm helps in the identification of the various steps, major decision


points and the variables needed to solve a problem. This are the concepts
that are needed for the development of a computer program.

 Algorithm helps in the decomposition of a large task into small manageable


subtasks. The decomposition helps in reducing the complexity of the
problem and make it solvable.
Roles of Algorithm in Problem Solving
 The atomic nature of the tasks/subtasks of the algorithm makes the decision
making process more rational in nature, since the subtasks are supported by
facts.

 Given different tasks, one algorithm can be applied in performing all the
tasks. This enhances the consistency and reliability of the problem solving
process.
Example of an Algorithm
Example:
Write an algorithm in natural language to calculate the area of a triangle (area
=1/2 * base * height)

Step 1: Start
Step 2: Select from the triangle the values for base and height
Step 3: Calculate the product of the values (i.e. base and height)
Step 4: Divide the product of base and height by 2
Step 5: The area is the result gotten after dividing base and height by 2
Step 6: Stop
CHAPTER 4: Representation of Algorithm
Representation of Algorithm
 Algorithms are written in natural language like English and other languages.
This method is found to be too wordy and confusing.

An algorithm can be expressed in two major ways:

 Pseudocode

 Flowchart
Pseudocode
 A pseudocode (pronounced Soo-doh-kohd) is another way of representing
an algorithm. It is considered as a non-formal language that helps
programmers to write algorithm.

 Pseudocode is a generic way of describing an algorithm without the use of


any specific programming language syntax.

 It is, as the name suggests, pseudocode - it cannot be executed on a real


computer, but it models and resembles real programming code, and is
written at roughly the same level of detail.
Pseudocode
 Pseudocode is a detailed description of instructions that a computer must
follow in a particular order. It is intended for human reading and cannot be
executed directly by the computer.

 There is no specific standard for writing a pseudocode exists. The word


“pseudo” means “not real,” so “pseudocode” means “not real code”.

 Following are some of the frequently used keywords while writing


pseudocode:

• INPUT • COMPUTE • PRINT • INCREMENT • DECREMENT • IF/ELSE • WHILE


• TRUE/FALSE
Pseudocode
 Example
Write a pseudocode to calculate the area of a triangle (area =1/2 * base *
height)

Step 1: Start
Step 2: Read base and height
Step 3: Product = base x height
Step 4: Area = product/2
Step 5: Print Area
Step 6: Stop
Benefits of Pseudocode
 Before writing codes in a high level language, a pseudocode of a program
helps in representing the basic functionality of the intended program.

 By writing the code first in a human readable language, the programmer


safeguards against leaving out any important step.

 Besides, for non-programmers, actual programs are difficult to read and


understand, but pseudocode helps them to review the steps to confirm that
the proposed implementation is going to achieve the desire output.
Flowchart
 A flowchart is a visual representation of an algorithm.

 A flowchart is a diagram made up of boxes, diamonds and other shapes,


connected by arrows.

 Each shape represents a step of the solution process and the arrow
represents the order or link among the steps.

 There are standardized symbols to draw flowcharts.


Flowchart
Flowchart
 Example
Draw a flowchart to calculate the area of a triangle (area = ½ * base * height)

Start

Read base, Read Height

Product = base * height


Area = Product/2

Print Area

Stop
General Rules of Flowcharting
 All boxed of the flowchart are connected with arrows not lines.

 All flowchart symbols have an entry point on top of the symbol with no
other entry points. The exit point for all flowchart symbols is on the bottom
except for the Decision symbol.

 The Decision symbol has two exit points; these can be on the side or the
bottom and one side.

 Generally a flowchart will flow from top to bottom. However, an upward


flow can be shown as long as it does not exceed 3 symbols.
General Rules of Flowcharting
 Connectors are used to connect breaks in the flowchart. Examples are:
 From one page to another page
 From the bottom of the page to the top of the same page
 An upward flow of more than 3 symbols.

 Subroutines and Interrupt programs have their own independent


flowcharts.

 All flowcharts starts with a Terminal Predefined Process (for interrupt


programs or subroutines) symbol.

 All flowcharts end with a terminal contentious loop.


Algorithm
Exercises

 Exercises1:
Write an algorithm to find the square of a number. Display the pictorial
representation of the algorithm using a flowchart.

 Exercise 2:
Draw a flowchart to solve the problem of a non-functioning light bulb.

 Exercise 3:
Write an algorithm to check whether a number is odd or even. Present
your algorithm in Psuedocode and flowchart
Algorithm
Exercises

 Exercises4:
write a pseudocode and draw a flowchart where multiple conditions are
checked to categorize a person as either child (<13), teenager (>=13 but
<20) or adult (>=20),based on age specified.

 Exercise 5:
Write pseudocode and draw a flowchart to accept 5 numbers and find their
average

 Exercise 6:
Write pseudocode and draw flowchart to accept numbers till the user
enters 0 and then find their average.
CHAPTER 5: Verifying Algorithms
Verifying Algorithm
 Why is verification of algorithm an important step in problem solving?

 Algorithm verification enables the software designer to ensure the


functionalities of all components are defined correctly, checked, and
verified in every possible way.

 For example, if we are told that the formula for the sum of first N natural
number is N(N+1)/2, how do we verify it?

We can check this by manually calculation the sum:


Let N = 9, then the sum is 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
Therefore using the formula N(N+1)/2 we can say 9*(9+1)/2 = 45
Verifying Algorithm
 To verify, we have to take different input values and go through all the steps
of the algorithm to yield the desired output for each input value and may
modify or improve as per the need.

 The method of taking an input and running through the steps of the
algorithm is sometimes called dry test or dry run.

 The method will help us to:


1. Identify any incorrect steps in the algorithm
2. Figure out missing details or specifics in the algorithm
CHAPTER 6: Coding
Coding
 After finalizing the algorithm, we need to convert the algorithm into the
format which can be understood by the computer to generate the
desired solution.

 Different high level programming languages can be used for writing a


program.

 It is equally important to record the details of the coding procedures


followed and document the solution. This is helpful when revisiting the
programs at a later stage.
Coding with C++
 C++ is a popular programming language.

 C++ is used to create computer programs.

 C++ is a cross-platform language that can be used to create high-


performance applications.

 C++ was developed by Bjarne Stroustrup, as an extension to the C


language.

 C++ gives programmers a high level of control over system resources and
memory.
C++ Syntax

#include <iostream> Line 1: #include <iostream> is a


using namespace std; header file library that lets us work
with input and output objects, such
int main() { as cout (used in line 5). Header files
cout << "Hello World!"; add functionality to C++ programs.
return 0;
} Line 2: using namespace std means
that we can use names for objects
and variables from the standard
library.
C++ Syntax
Line 3: A blank line. C++ ignores white
space.
#include <iostream>
using namespace std; Line 4: Another thing that always
appear in a C++ program, is int
int main() { main(). This is called a function. Any
cout << "Hello World!"; code inside its curly brackets {} will be
return 0; executed.
}
Line 5: cout (pronounced "see-out") is
an object used together with the
insertion operator (<<) to
output/print text. In our example it
will output "Hello World".
C++ Syntax
Line 6: return 0 ends the main
function.
#include <iostream>
using namespace std; Line 7: Do not forget to add the
closing curly bracket } to actually end
int main() { the main function.
cout << "Hello World!";
return 0;
}
C++ Syntax
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}
The cout object, together with the <<
operator, is used to output
#include <iostream>
values/print text: using namespace std;

int main() {
cout << "Hello World!";
cout << "I am learning
C++";
return 0;
}
Variables
 Variables are containers for storing data values.

 In C++, there are different types of variables (defined with different keywords),
for example:

int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
Variables
 To create a variable, you must specify the data type and assign it a value.
type variable = value;

 Where type is one of C++ types (such as int), and variable is the name of the
variable (such as x or myName). The equal sign is used to assign values to the
variable.

int myNum = 15;


cout << myNum; int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
int myNum; string myText = "Hello"; // String (text)
myNum = 15; bool myBoolean = true; // Boolean (true or false)
cout << myNum;
Flow of Control
 Algorithms use control flow to make decisions about which order to do
things.

 They can repeat actions or start new actions based on new information.

 Computer programs use sequence, selection and iteration to control the


flow of the program.

 These elements allow the program to make choices, change direction or


repeat actions.
Flow of Control
Sequence Flow

 The most basic algorithm uses sequences to present


a list of instructions to be followed one after the
other, step by step.

Example
1. unlock the door
2. open the door
3. enter the room
4. switch on the light
5. close the door behind you
Flow of Control
Selection Flow

 A selection is used to make choices based on information. An algorithm can


be made more intelligent by using IF, THEN and ELSE to repeat instructions
or move to different parts of the program.

 Selection flow are of three types


 Single Alternative

 Double Alternative

 Multiple Alternative
Flow of Control
Selection Flow

Single Alternative
if (condition) {
// statement goes here
}

 Example
if (20 > 18) {
cout<< "20 is greater than 18";
}
Flow of Control
Selection Flow  Example
int time = 20;
Double Alternative if (time < 18) {
if (condition) { cout<< "Good day.";
// statement if true } else {
} else { cout<< "Good evening.";
// statement if false }
} // Outputs "Good evening."
Flow of Control
Selection Flow  Example
int time = 22;
Multiple Alternative if (time < 10) {
if (condition1) { cout<< "Good morning.";
// condition1 is true } else if (time < 20) {
} else if (condition2) { cout<< "Good day.";
//condition1 is false & } else {
condition2 is true cout<< "Good evening.";
} else { }
condition1 and condition2 // Outputs "Good evening."
are both false
}
Flow of Control
Selection Flow

Multiple Alternative
 The algorithm about entering the room could be changed to
account for different conditions. For instance, it could change
to:
1. IF the door is locked, THEN unlock the door, ELSE do nothing
(go to next instruction)
2. IF the door is closed, THEN open the door, ELSE do nothing
3. Enter the room`
4. IF the room is dark, THEN switch on the light, ELSE do nothing
5. Close the door behind you.
Flow of Control
Selection Flow

Multiple Alternative
 The sequence of actions that is carried out is selected based upon the
information.
 The only way for a computer to discover the circumstances is to collect inputs
and compare them to known values.
 In this case, known values would be values such as 'locked' or 'unlocked',
'closed' or 'open'.
 The computer looks at the door and checks to see if its current state matches
'closed' and 'locked'. If it matches 'locked', the door needs to be unlocked.
Otherwise, nothing should be done.
Flow of Control
Selection Flow

Multiple Alternative
 The selection IF-THEN-ELSE is useful if the choices are binary, e.g.
True or False.

 The alternative to the IF-THEN-ELSE structure is the CASE structure.


Using CASE, the algorithm searches a list of options until it finds the
correct condition. For example, on a multiple-choice quiz, the answers
might be A, B, C or D - the correct condition is either A, B, C or D.

 Basically, IF-THEN-ELSE looks for the correct option from two choices
where CASE looks at the correct option from multiple choices.
Flow of Control
Selection Flow switch(expression) {
case x:
Switch Case // code block
break;
 The switch case statement is used case y:
when we have multiple options and // code block
we need to perform a different task break;
for each option. default:
// code block
}
Flow of Control
Selection Flow

Switch Case
Flow of Control
Iteration Flow

 Iteration is the process of repeating sections of a program to achieve a


particular target or goal.

 Computer programs can use different types of loops:


 infinite loops - repeat forever
 count-controlled loops - repeat a set amount of times
 condition-controlled loops - repeat until something happens

 Loop: Is a method used in programming to repeat a set of instructions.


Flow of Control
Iteration Flow  For example, on a desktop computer,
the operating system has a program
Infinite loops that continually checks your USB
ports to see if you have plugged in a
 A sequence in an infinite loop keeps device. Even after you have plugged
repeating until the user terminates in a device, it still continues to check
the program or it crashes. for any new devices.

for(int i=1; i>=1; i++){


cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
Flow of Control
Iteration Flow for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
Count-controlled loop
Statement 1 is executed (one time)
 Count-controlled loops are used before the execution of the code block.
to make a computer do the same
thing a specific number of times. Statement 2 defines the condition for
executing the code block.
 The count-controlled loop can be
described as a FOR loop. The Statement 3 is executed (every time)
program repeats the action FOR after the code block has been
a number of times. executed.
Flow of Control
Iteration Flow  Statement 1 sets a variable before
the loop starts (int i = 0).
Count-controlled loop
 Statement 2 defines the condition
 Example for the loop to run (i must be less
than 5). If the condition is true, the
for (int i=0; i < 5; i++) loop will start over again, if it is
{ false, the loop will end.
cout<< i << "\n";
}
 Statement 3 increases a value (i++)
each time the code block in the
loop has been executed.
Flow of Control
Iteration Flow

Count-controlled loop

 Example

for (int i=0; i < 5; i++)


{
cout << i << "\n";
}
Flow of Control
Iteration Flow  Both while loops and do-while loops are
condition-controlled, meaning that they
Condition-controlled loops continue to loop until some condition is
met.
 A program could be made more
intelligent by programming it to  Both while and do-while loops alternate
avoid hazards. between performing actions and testing
for the stopping condition.
Flow of Control
Iteration Flow while( condition )
body;
Condition-controlled loops
 where the body can be either a single
statement or a block of statements within
While Loop
{ curly braces }.
 While loops check for the
 Example:
stopping condition first, int i = 0;
and may not execute the while( i < 5 )
body of the loop at all if the cout << "i = " << i++ << endl;
cout << "After loop, i = " << i << endl;
condition is initially false.
Flow of Control
Iteration Flow do {
body;
} while( condition );
Condition-controlled loops
 where the body can be either a single
do-while Loop statement or a block of statements within
{ curly braces }.
 do-while loops are exactly
 Example:
like while loops, except that int month;
the test is performed at the do {
cout << "Please enter your birth month” > ";
end of the loop rather than cin >> month;
} while ( month < 1 || month > 12 );
the beginning.
Flow of Control
Iteration Flow

Condition-controlled loops
Summary
 An algorithm is defined as a step-by-step procedure designed to perform an operation
which will lead to the desired result, if followed correctly.
 Algorithms have a definite beginning and a definite end, and a finite number of steps.
 A good algorithm, which is precise, unique and finite, receives input and produces an
output.
 In order to write effective algorithms we need to identify the input, the process to be
followed and the desired output.
 A flowchart is a type of diagram that represents the algorithm graphically using boxes of
various kinds, in an order connected by arrows.
 An algorithm where all the steps are executed one after the other is said to execute in
sequence.
 Decision making involves selection of one of the alternatives based on outcome of a
condition.
 An algorithm may have a certain set of steps, which are repeating for a finite number of
times, such an algorithm is said to be iterative.
 There can be more than one approach to solve a problem and hence we can have more
than one algorithm for a particular problem.
 The choice of algorithm should be made on the basis of time and space complexity.
Exercises
1. Write pseudocode that reads two numbers and divide one by another and display the quotient.

2. Write the pseudocode to print all multiples of 5 between 10 and 25 (including both 10 and 25).

3. Give an example of a loop that is to be executed a certain number of times.

4. Write an algorithm to find the greatest among two different numbers entered by the user.

5. Write an algorithm that performs the following: Ask a user to enter a number. If the number is
between 5 and 15, write the word GREEN. If the number is between 15 and 25, write the word BLUE. if
the number is between 25 and 35, write the word ORANGE. If it is any other number, write that ALL
COLOURS ARE BEAUTIFUL.

6. Write an algorithm that accepts four numbers as input and find the largest and smallest of them.

You might also like