Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Algorithms - 2

Similar presentations


Presentation on theme: "Introduction to Algorithms - 2"— Presentation transcript:

1 Introduction to Algorithms - 2
Dr. Khizar Hayat Associate Prof. of Computer Science

2 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

3 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 totaltotal+1 End repeat OR while total ≤50 End while

4 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

5 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

6 Algorithm to sum five numbers input by the user
Start count 0 begin set count0 set sum0 repeat until count=5 get num set countcount+1 set sumsum+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

7 Algorithm to compute the GCD of two numbers
begin get numA get numB if numA > numB then set maqsnumA set m_AlaihnumB else set maqsnumB set m_alaihnumA end if set baqimaqs mod m_alaih while baqi ≠ 0 do set maqsm_alaih set m_alaihbaqi 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

8 Exercises Draw a flowchart that reads names of 50 students in the class and display it. Page of notes Page 21 of notes Any sum in Omani currency?


Download ppt "Introduction to Algorithms - 2"

Similar presentations


Ads by Google