0% found this document useful (0 votes)
64 views

Introduction To Ict.: (Algorithms.) Lecture # 15-16 By: M.Nadeem Akhtar. Lecturer. Department of CS & IT

This document provides an introduction to algorithms and problem solving. It defines algorithms as a precise sequence of limited, unambiguous steps that terminates with a solution. It discusses how to define a problem clearly, think of possible solutions, and apply the best solution. It provides an example algorithm for crossing a river with goods under constraints. The document notes that algorithms are useful because they provide a recipe to follow to solve a problem.

Uploaded by

Abdullah Jutt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Introduction To Ict.: (Algorithms.) Lecture # 15-16 By: M.Nadeem Akhtar. Lecturer. Department of CS & IT

This document provides an introduction to algorithms and problem solving. It defines algorithms as a precise sequence of limited, unambiguous steps that terminates with a solution. It discusses how to define a problem clearly, think of possible solutions, and apply the best solution. It provides an example algorithm for crossing a river with goods under constraints. The document notes that algorithms are useful because they provide a recipe to follow to solve a problem.

Uploaded by

Abdullah Jutt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

INTRODUCTION TO ICT.

(ALGORITHMS. )
Lecture # 15-16
By:
M.Nadeem Akhtar.
Lecturer.
Department of CS & IT.

1
URL: https://sites.google.com/site/nadeemcsuoliict/home/lectures
DEFINING THE PROBLEM
• A well-defined problem has five components:

– A clearly defined initial situation given.


– A clearly defined goal.
– A clearly defined set of resources.
– A clearly defined constraints.
– Ownership.
CASE STUDY
• You are at a river that you want to cross with
all your goods. Your goods consist of a
chicken, a bag of grain and your cat. You have
to cross the river in your boat but can only
take one passenger with you at a time – the
chicken, the cat or the bag of grain. You can’t
leave the chicken alone with the grain as the
chicken will eat the grain. You can’t leave your
cat alone with the chicken as cat will eat the
chicken. However, you know that cat does not
eat grain. How do you get everything across
the river intact?
PROBLEM
• Initial Situation: You, the Chicken, the Bag of
Grain and the Cat are on one bank of a river
with access to a boat.

• Resources: The boat and your knowledge and


problem-solving skills.

• Constraints: You can take only one passenger,


you must not leave Cat with the Chicken, you
must not leave the Chicken with the Grain.
• Goal: You, the Chicken, the Bag of Grain and
the Cat on the opposite bank of river.

• Ownership: You will be involved in planning


the solution and carrying it out.
SOLUTION
• Take the chicken across the river and leave it on
the other side. Return to where you have left Cat
and the Grain.

• Take Cat across the river and leave him on the


other side. Take back the chicken.

• Leave the chicken where you started. Take the


bag of grain across the river and leave it with the
Rover.

• Go back and fetch the chicken and take it across


the river with you.
SOLVING PROBLEMS
When faced with a problem:
1. We first clearly define the problem
2. Think of possible solutions
3. Select the one that we think is the best
under the prevailing circumstances
4. And then apply that solution
5. If the solution woks as desired, fine; else we
go back to step 2
7
SOLVING PROBLEM IS ITERATIVE PROCESS
• It is quite common to first solve a problem for a
particular/special case
• Then for another
• And, possibly another
• And watch for patterns and trends that emerge
• And to use the knowledge form those patterns
and trends in coming up with a general solution

8
EXAMPLE
• 1+1=2
• 2+1=3
• 3+1=4
• 4+1=5
= 6, 7, 8…
in first 2, 3 iteration the child discover a pattern i.e. the
answer is always one more than the previous answer.
Despite added two numbers he discovered the trend or
pattern.
That’s how generally people work. 1st they solve the
problem for a particular case, then another case and so
on. And discover trends and patterns in the problem.
And from those trends and pattern they make a
general purpose solution. Which may be efficient.
• If you want to solve a problem, it helps if you have
experienced that problem or similar ones before.

• Generally, there are many ways of solving a


problem. The experienced people find the method
easily to solve a problem. So again experienced
counts.

• The process or set of processes that can be used to


solve a problem is termed as the “algorithm”.
ALGORITHM
• Sequence of steps.
That can be taken to solve a given problem.

STEPS
Sequence
• Steps:
When we divide a task into smaller task, we
may call them steps.
Example: Walking

• Algorithm:
Sequence of steps, these steps must be in
precise sequence.
Example: making an egg.
EXAMPLES
1) Addition (ADDING TWO NUMBERS)
2) Conversion from decimal to binary.
3) The process of boiling an egg.
4) The process of mailing a letter.
5) Sorting (Tallest person)
6) Searching (google follow an algorithm to
search your appropriate page)
Let us write down the algorithm for a
problem that is familiar to us

Converting a decimal number into binary

14
Algorithm for a problem
• Converting a decimal number into binary.
2 125 Remainder Algorithm in Structured English
2 62 1
1. Write the decimal number.
2 31 0
2 15 1 2. Divide by 2; write quotient and
remainder.
2 7 1
2 3 1 3. Repeat step 2 on the quotient;
keep on repeating until the
2 1 1 quotient becomes zero.
0 1
4. Write all the remainder digits
in the reverse order (last
remainder first) to form the final
result.
Points to Note:
1) The process consists of repeated application
of simple steps.
2) All steps are unambiguous (clearly defined).
3) We are capable of doing all steps.(all steps are
executable)
4) Only finite number of steps is need to be
taken.
5) The required result will be found.
6) Moreover, the process will stop at that point.
Algorithm (Better Definition)
• 1st Definition:
Sequence of steps that can be taken to solve a
problem.

• Better Definition:
A precise sequence of a limited number of
unambiguous, executable steps that terminates
in the form of a solution.
THREE REQUIREMENT
1. Sequence is:
a. Precise
b. Consists of limited number of steps

2. Each step is:


a. Unambiguous
b. Executable

3. The sequence of steps terminates in the


form of a solution.
WHY ALGORITHMs ARE USEFULL?
• Once you write an algorithm for a particular
problem. That’s it.

• Next time the same problem arrived again,


you don’t need to do discovery process. It is
already written you just follow it.

• Once the algorithm is known, that recipe you


follow blindly, without thinking.
WHAT IS AN ALGORITHM?
• So, algorithm is knowledge through a problem
can be solved.

• So, to solve a particular problem if you want


to know what kind of knowledge is required.
All of that is embedded in the algorithm of
this problem.
NOTE
• Once you write an algorithm, Do write it down
somewhere reason behind it to use that
algorithm in future.

• If you write something. To modify and make it


more better(optimize) is easy.

• If you want to tell someone about your


algorithm. If it is in written form then it is easy
to tell.
ALGORITHM TECHNIQUES
• Different kind of algorithm strategies are there
which people follow to write an algorithm:

– Greedy Algorithm
– Deterministic Algorithm
– Randomized Algorithm
TRAVELING SALESMAN PROBLEM
• A salesman needs to visit each of the n cities.

120 C 70
B F
60
100 40 30
80 D 50
A G
90
70 110
E

• Is there is a route that takes the salesman


through every city and back to starting city A at a
cost of $520?
A FEW QUESTIONS
• Is that the best possible sequence?
• How do you know?
• How do I determine the best sequence?
How do I determine the sequence that I draw
is the best one, shortened one and optimist
one.

Solution: you have to list down all possible


combinations, compute all possible distances.
Have to find minimum distance.
SELECTION OF ALGORITHMIC
APPLICATION AREAS
• Search
• Sort
• Cryptography
• Parallel (algorithm to run on parallel
computer)
• Numeric
• Graphical
• Quantum Computing
• Combinatory
ALGORITHM REPRESENTATION
• Generally, software developers represent
them in one of three forms:

– Pseudo Code
– Flowcharts
– Actual Code
– Structured English
FLOWCHART
• A graphical representation of a process (e.g.
an algorithm), in which graphic objects are
used to indicate the steps & decisions that are
taken as the process moves along from start
to finish.
Start or stop

Process

Input or output
Flowchart
Elements Decision

Flow line
Connector

Off-page connector
PSEUDO CODE
• Language that is typically used for writing
algorithms.

• Similar to programming language, but not as


rigid.

• Plain English plus some formulas are used to


write pseudo code.
STRUCTURED ENGLISH
• Structured English is a very limited, highly
restricted subset of the English language.

• Non-programmers should also find it easy to


understand.

• There is no standard for structured English.


ACTUAL CODE
• Algorithm in the form of actual code written in
any programming language like C++, Java etc.
ALGORITHM BUILDING BLOCKS
• All problems can be solved by employing
any one of the following building blocks or
their combinations:

1. Sequences (of instructions).


2. Conditionals .
3. Loops (repetition).

• An algorithm is used any one of the


building blocks or its combination.
SEQUENCES
• A sequence of instructions that are executed in the
precise order they are written in:
Pseudo Code Flowchart

Calculate Percentage
Calculate Percentage
Sum ← Num1 + Num2
Average ← Sum/2 Sum ← Num1 + Num2

Average ← Sum/2
CONDITIONALS
• Select between alternate courses of action
depending upon the evaluation of condition:
Pseudo Code Flowchart

True False
If (condition = true) condition

statement block 1
Else
statement statement
statement block 2 block 1 block 2
End If
LOOPs
• Loop through a set of statements as long as a
condition is true:
Pseudo Code Flowchart
Loop while (condition=true)
Do statement block
End Loop

statement
True
block condition

False
EXAMPLE OF CONDITIONS
• Toss a coin, if the head will occur, then I will
not do my homework assignment. If the tail
will occur, then I will do my homework
assignment.

• So, the conditions always have one of two


outcomes and course of action is determine
accordingly.
REMEMBER
• With the help of these three building blocks
i.e. Sequences, Conditions and Loops. you can
write any algorithm.

• We will go through the problem statement


and present the algorithm in three different
formats:
1. Pseudo Code
2. Flowchart
3. Actual Code
Example
• Write an Pseudo code, Actual code and draw a
flowchart that calculates the sum and average of
two numbers.

• Pseudo code
– Input Number1
– Input Number2
– Sum ← Number1 + Number2
– Average ← Sum/2
– Output Sum, Average

38
Flow Chart
START

Input
Num1, Num2

Sum ← Number1 +
Number2

Average ← Sum/2

Output Sum,
Average

STOP 39
ACTUAL CODE IN PASCAL
Program FindSumAverage;
Var
Number1, Number2, Sum, Average : Real;
Begin
write (‘First number? ’); Readln(Number1);
write (‘Second number? ’); Readln(Number2);

Sum := Number1 + Number2;


NOTE: Don’t
Average = Sum / 2;
worry if you
Writeln(‘Their sum is’, Sum: 5:2);
don’t
Writeln(‘Their average is’, Avg: 5:2); understand this
End. code for now;
you will - later!
40
Example
• Write an Pseudo code, Actual code and draw a
flowchart that will calculate the roots of a quadratic
equation.
ax 2  bx  c  0
• Hint: d = sqrt ( b 2  4ac ), and the roots are:
x1 = (–b + d)/2a and x2 = (–b – d)/2a

• Pseudo code
– Input coefficients (a, b, c) of the quadratic equation
– Calculate d = sqrt ( b  4ac )
2

– Calculate x1 = (–b + d)/2a


– Calculate x2 = (–b – d)/2a
– Output x1 and x2
41
Flow Chart
START

Read Input
a, b, c

d = sqrt(b x b – 4 x a x c)

x1 = (–b + d) / (2 x a)

X2 = (–b – d) / (2 x a)

Write Output
X1, X2

STOP

42
PROBLEM STATEMENT
• Converting a decimal number into binary.

2 125 Remainder
2 62 1
2 31 0
2 15 1
2 7 1
2 3 1
2 1 1
0 1

12510 = 11111012
SOLUTION IN PSEUDO CODE
1) Let the decimal number be an integer x, x > 0
(whenever you write an algorithm you take
assumptions, so in this case we take assumption that
number is integer and it must be greater than 0.)
2) Let the binary equivalent be an empty string y
3) Repeat while x > 0 {
Determine the quotient & remainder of x ÷ 2
y = CONCATENATE(remainder, y)
x = quotient
}
4) Output y
5) Stop
Start Flowchart of Decimal
to Binary Conversion
Read x

Yes Find quotient y = CONC(remainder, y)


x>0 ? & remainder
x = quotient
of x ÷ 2
No

Output y
x is the decimal number
Stop y is the binary equivalent 45
DECIMAL TO BINARY CONVERSION IN JAVASCRIPT

<SCRIPT type=“text/javascript”>
x = 125; // x is the decimal number
y = “”; // y is the binary equivalent
while ( x > 0) {
remainder = x % 2;
quotient = Math.floor( x / 2 );
y = remainder + y; NOTE: Don’t
x = quotient; worry if you
} don’t
understand this
document.write(“y = ” + y);
code for now;
</SCRIPT> you will - later!
46
EXAMPLES
• Students appears in an examination, which
consists of total 10 subjects. Each subject having
maximum marks of 100.
– The roll number of the student, his/her name, and the
marks obtained by him/her in various subjects, are
supplied as input data.
– We want to make a list of only those students who
have passed (obtained 50% or more marks) in the
examination.
– In the end, we also want to print out the total number
of students who have passed.
– The input data of all students is terminated by a trailer
record, which has sentinel value of 9999999 for Roll
No.
Start Flowchart for the Exam Process
Count = 0

Read
Input
Add 1 to Count

Write
Is RollNo = No Add marks of all Output
999999? Subjects (Total) Yes
Yes No
Percentage = Is percentage
Write Count
Total / 10 = >50?
48
Stop
SOLUTION IN PSEUDO CODE
1) Set Count to zero
2) Read first student record
3) Repeat while RollNo is not equal to 9999999 {
Calculate Total Marks
Calculate Percentage = Total / 10
IF Percentage => 50
Write Output
Add 1 to Count
ENDIF
}
4) Write Count
5) Stop
ACTUAL CODE OF EXAMPLE IN JAVASCRIPT
<SCRIPT type=“text/javascript”>
var marks = new Array(5);
var student, roll;
roll = window.prompt("Enter Student Roll No","");
if(roll=="999999"){
document.write(“Program Terminate”);
exit();
}else{
student = window.prompt("Enter Student Name","");
for(k=0; k<marks.length; k++){
marks[k] = parseInt(window.prompt("Enter Student subject marks",""));
}
var total = marks[0] + marks[1] + marks[2] + marks[3] + marks[4];
var percentage = total/5;

if(percentage >= 50){


document.write("<b>Hi, Congratulations you are pass" + "</b><br>");
document.write("<b>Student Name: </b>" + student + "<br>");
document.write("<b>Roll No: </b>" + roll + "<br>");
document.write("<b>Percentage: </b>" + percentage + "<br>");
}else{
document.write("Hi " + student + " Roll no " + roll + " You are fail,
your percentage is " + percentage);
}
}
</SCRIPT> 50
EXAMPLES
• Draw a flowchart and write pseudo code that
reads three numbers, determine the largest
number and print the largest number with an
identifying message?
SOLUTION IN PSEUDO CODE
1) Let the number be integer and non-negative
2) Set the largest number MAX
2) Read input N1, N2, N3
3) IF(N1 > N2 && N1 > N3)
MAX = N1
ENDIF
IF(N2 > N1 && N2 > N3)
MAX = N2
ENDIF
ELSE
MAX = N3
4) Print “The largest number is: ” MAX
5) Stop
Flowchart of the Example
START

Read A, B, C

Yes If
No If No
A is larger B>A && B>C
A>B && A>C
Print A

Yes
B is larger C is larger
Print B Print C

STOP
ACTUAL CODE OF LARGEST NO. EXAMPLE IN JAVASCRIPT
<SCRIPT type=“text/javascript”>

var a = window.prompt(“enter 1st positive integet”, “”);


var b = window.prompt(“enter 2nd positive integet”, “”);
var c = window.prompt(“enter 3rd positive integet”, “”);

if ( a > b && a > c) {

document.write(“The largest no is:” + a);


NOTE:
} else {
if ( b > a && b > c) { Don’t worry
document.write(“The largest no is:” + b); if you don’t
} else {
document.write(“The largest no is:” + c);
understand
} this code
for now;
}
you will -
</SCRIPT> later! 54
EXAMPLE
• A company plans to pay bonus to their employees, the
details are given below:

– Those earning Rs. 30,000 or above are to be paid 20 percent of


their salary.

– Those earning less than Rs. 30,000 are to be paid Rs. 1000

– The input records contain the employee number, name and


salary of the employees.

– The output to be printed should contain the employee number,


name, amount of bonus and new salary to be paid to each
employee.

• HINT: Formula to calculate Bonus is:


Pros and Cons of Flowcharts (1)
• I personally don’t find flowcharts very useful

• The process of writing an algorithm in the form of a


flowchart is just too cumbersome

• And then converting this graphical form into code is


not straight forward

• However, there is another kind of flowcharts –


called Structured Flowcharts – that may be better
suited for software developers
56
Pros and Cons of Flowcharts (2)
• The good thing about flowcharts is that their
symbols are quite intuitive and almost universally
understood

• Their graphical nature makes the process of


explaining an algorithm to one’s peers quite
straightforward

57
Pros and Cons of Pseudo Code (1)
• Quite suitable for SW development as it is closer in
form to real code

• One can write the pseudo code, then use it as a


starting point or outline for writing real code

• Many developers write the pseudo code first and


then incrementally comment each line out while
converting that line into real code

58
Pros and Cons of Pseudo Code (2)
• Pseudo code can be constructed quite quickly as
compared with a flowchart

• Unlike flowcharts, no standard rules exist for writing


pseudo code

59

You might also like