Introduction to Algorithms - 2 Dr. Khizar Hayat Associate Prof. of Computer Science
What can a computer do An algorithm can be written using six basic computer operations: A computer can receive (input) information, e.g. read name get x A computer can display (output) information, e.g. write “the average is “, avg display num print “Hello!” A computer can perform arithmetic operations, e.g. set total total + numb A computer can assign value to a variable, e.g. set counter 0 set total price+tax
What can a computer do A computer can compare two pieces of information to select one of two actions, e.g. if number < 0 then add 1 to neg_number else add 1 to pos_number end if A computer can repeat a group of actions, e.g. repeat untill total=50 read num write num set totaltotal+1 End repeat OR while total ≤50 End while
Algorithm to add two numbers begin get num1 get num2 set sum num1 + num2 display sum end Start Read Num1 Read Num2 Sum Num1 + Num2 What about: The difference of two numbers? The sum and difference of two numbers? Display Sum Stop
Algorithm to input two numbers and print the smaller number Start begin get num1 get num2 if num1 < num2 then display num1 as smaller else display num2 as smaller end if end Read Num1 Read Num2 Num1 < Num2? No What about: The largest of two numbers? The largest of three numbers? The median of three numbers? Yes Display Num1 as min Display Num2 as min Stop
Algorithm to sum five numbers input by the user Start count 0 begin set count0 set sum0 repeat until count=5 get num set countcount+1 set sumsum+num end repeat display sum as the total end sum 0 Read Num count count + 1 sum sum + Num count = 5? No What about: Sum of N numbers? Average of N numbers? Entering numbers till ‘-1’ is entered? The sum of first 20 numbers? Yes Display sum as total Stop
Algorithm to compute the GCD of two numbers begin get numA get numB if numA > numB then set maqsnumA set m_AlaihnumB else set maqsnumB set m_alaihnumA end if set baqimaqs mod m_alaih while baqi ≠ 0 do set maqsm_alaih set m_alaihbaqi end while display m_alaih as GCD end Display M_Alaih as GCD Stop Maqs NumA M_Alaih NumB Start Read NumA Read NumB NumA > NumB? Yes No Maqs NumB M_Alaih NumA Baqi = 0? Maqs M_Alaih M_Alaih baqi Baqi Maqs mod M_Alaih Euclid’s Algorithm
Exercises Draw a flowchart that reads names of 50 students in the class and display it. Page 16-17 of notes Page 21 of notes Any sum in Omani currency?