You are on page 1of 15

Introduction to Algorithms

CSBP119 – Algorithms & Problem Solving


Chapter 1
What is an • A finite sequence of well-defined
step-by-step instructions to solve
Algorithm? a given problem
Download the syllabus from Blackboard
Algorithm for downloading the Syllabus:
1.      open an internet browser
2.      Place the curser at the address bar
3.      type elearning.uaeu.ac.ae 
4.      press enter
5.      type your username in the Username textbox
6.      type your password in the Password textbox
7.      click on "Log In" button
8.      Go to the "Courses" tab
9.      Click on your course name
10.      Click on "Course Document" in the left panel
11.      Click on the link to download the syllabus
What can a computer do?

Input Process Output


CPU & Main Memory

http://math.hws.edu/javanotes/c1/s1.html
Exercises
• Write an algorithm for calculating
the area of a rectangle

• Write an algorithm for calculating


the average of 5 test scores. 
Exercise
• Calculate the square root of a given number if it's
positive. Otherwise display an error message. 
Exercise
• Suppose the cost of sending a fax is as follows:
o  Service charge: $3 
o  $0.20 per page for the first 10 pages
o  $0.10 for each additional page
• Write an algorithm that calculates and displays
the cost of sending a fax, given the number of
pages. 
Exercise
• Write an algorithms that finds the largest of 4
given numbers
Think about this … 

• Given an unknown value, X, how can we


figure out if it's an odd or even number?
• An even number is a multiple of 2
• When we divide X by 2, we get a whole
number
• e.g.  8/2 is 4  but 7/2  is 3.5
Modulo 
• The modulo operation (or mod) returns the remainder
of division
• Examples:
    7 mod 2  is 1
    3 mod 2 is 1
    2 mod 2 is 0
    4 mod 2 is 0
• In programming languages, we use % for mod (e.g.7%2)
Exercise
• Given the time in 24-hour format, how can we covert
it to 12-hour format?

• Example: if the hour is 18, we want to convert it to 6


Repetition
• What is a loop?
• A piece of code that runs repeatedly
• Going back “up” in the program
Exercise
• Write an algorithm that finds the maximum of 100 given numbers. 

• Solution:
1. Read a number and store it in max
2. Repeat the following 99 times:
a) Read a number and store it in X
b) If X > max then max =x
3. Display max

You might also like