Presentation is loading. Please wait.

Presentation is loading. Please wait.

Software and Algorithms

Similar presentations


Presentation on theme: "Software and Algorithms"— Presentation transcript:

1 Software and Algorithms
Chapter 3 Software and Algorithms Dr. Khaled Wassif Fall CS111

2 CHAPTER OUTLINE What is Software? Programming Languages
Why using Algorithms? What is an Algorithm? Representing Algorithms Operations of Algorithms Input / Output Computations If-else-endif While-endwhile CS111 Introduction to Computers By Dr. Khaled Wassif

3 What is Software (S/W)? S/W consists of a set of machine-readable instructions, called programs, that cause the computer to perform a task. There are two basic types of software: Applications software: Designed to satisfy a user’s specific needs. May be custom or packaged (off-the-shelf). System software: Without it H/W and applications S/W are useless. Operating System – Coordinate all hardware components. Compilers – Translate source program into object program. CS111 Introduction to Computers By Dr. Khaled Wassif

4 Programming Languages
Enables a programmer to write programs that are more or less independent of a particular type of computer. Considered high-level languages because they are closer to human languages and further from machine languages. Generations of computer languages are: First generation: machine language Second generation: assembly language (low-level language) Third generation: high-level programming languages, as C, C++, and Java. Forth generation: query languages; used to access databases, as SQL Fifth generation: artificial intelligence languages, as Prolog, and Lisp CS111 Introduction to Computers By Dr. Khaled Wassif

5 Algorithms An algorithm is a step by step method for solving a problem. We use algorithms all the time in our daily life, for example: Cooking recipes Directions how to get to places Performing mathematical tasks such as: Calculate the students' GPA Calculate the interests for invested money in a bank An algorithm for calculating the area of a square: Step 1. Get the value of Side Step 2. Area = Side * Side Step 3. Print the value of Area CS111 Introduction to Computers By Dr. Khaled Wassif

6 History of Algorithms Named after the Persian mathematician Muhammad Ibn Musa Al-Khwarizmi ( in Khwarizm, Uzbekistan) developed a strategy for calculating heritage proportions using algebraic methods. His name was turned into Algorism and that evolved Algorithm. CS111 Introduction to Computers By Dr. Khaled Wassif

7 History of Algorithms (cont.)
The oldest known algorithm is probably Euclid's Algorithm to determine the greatest common divisor (GCD) of two integers (circa B.C). Method: To find the GCD of two numbers, repeatedly replace the larger by subtracting the smaller from it until the two numbers are equal. Only subtraction and comparison operations are needed. Example: GCD of 132 and 168 36 132 36 96 36 60 36 24 12 24 12 12 So the GCD of 132 and 168 is 12. CS111 Introduction to Computers By Dr. Khaled Wassif

8 Why Using Algorithms? If we can specify an algorithm to solve a problem, then we can automate its solution. Why use a computer? Computers are fast: They can perform operations without errors at speed unattainable by human beings. They can store very large amount of information: Human beings have a difficulty managing and keeping track of a large number of objects. They are not task specific: They can be programmed to perform different tasks. Most other tools can do only one thing. Their tasks can be automated: Computers are excellent at performing the same task over and over again on similar pieces of data. CS111 Introduction to Computers By Dr. Khaled Wassif

9 What is an Algorithm? An algorithm is a well-ordered collection of unambiguous and effectively computable operations that, when executed, produces a result and halts in a finite amount of time. An algorithm is well-ordered: Each step of the algorithm is executed in the order in which it is written, or else the order is clearly stated. An algorithm is unambiguous: It must be clearly stated, in terms that the computer understands An algorithm is effectively computable: It must be possible for the computer to perform the operation and produce a result An algorithm must halt in a finite amount of time: It must even if it would take centuries to finish CS111 Introduction to Computers By Dr. Khaled Wassif

10 Representing Algorithms
Algorithms can be expressed in any language, from natural languages to formal programming languages or others. Natural Languages (e.g. English, French) Formal Programming Languages (e.g. Java, C++) Something else? What language to use? Expressive Clear Precise and unambiguous CS111 Introduction to Computers By Dr. Khaled Wassif

11 Representing Algorithms: Natural Languages
Example: Given is a natural number n. Compute the sum of numbers from 1 to n. Representation with Natural Language Initially, set the value of the variable result to 0 and the value of the variable i to 1. When these initializations have been completed, begin looping until the value of the variable i becomes greater than n. First, add i to result. Then add 1 to i and begin the loop all over again. Disadvantages: Too verbose Unstructured Too rich in interpretation (ambiguous) Imprecise CS111 Introduction to Computers By Dr. Khaled Wassif

12 Representing Algorithms: Formal Programming Languages
Example: Given is a natural number n. Compute the sum of numbers from 1 to n. Representation with Formal Programming Language (Java) public class Sum { public static void main(String[] args) { int result = 0; int n = Integer.parseInt(args[0]); int i = 1; while (i <= n) { result = result + i; i = i + 1;} System.outp.println(result);}} Disadvantages: Too many implementation details to worry about Too rigid syntax CS111 Introduction to Computers By Dr. Khaled Wassif

13 Representing Algorithms: Pseudo-code
We need a compromise between the two: Pseudo-code Computer scientist use Pseudo-code to express algorithms: English like constructs (or other natural language) Modeled to look like statements in typical programming languages. Not actually executed on computers. Allows us to think out a program before writing the code for it. CS111 Introduction to Computers By Dr. Khaled Wassif

14 Pseudo-Code: Input/Output and Computation
Input operations: Allow the computer to receive from the outside world data values to use in subsequent computations. General Format: get value for variable Output Operations: Allow the computer to communicate results of the computations to the outside world. General Format: print value of variable print the message “text” Computation: Performs a computation and stores the result. General format: set variable to expression CS111 Introduction to Computers By Dr. Khaled Wassif

15 Pseudo-Code: Variables
A variable is a named storage: A value can be stored into it, overwriting the previous value. Its value can be copied. Examples: get value for A Get a value to the variable A. set A to 3 The variable A holds the value 3 after its execution. set A to A + 1 Add 1 to the value of A (A is now 4) print value of A Display the current value of A (4) CS111 Introduction to Computers By Dr. Khaled Wassif

16 Pseudo-Code: Writing an Algorithm
Example: Given the radius of circle, determine the area. Decide on names for the objects in the problem and use them consistently, e.g. radius, area (we call them variables) Use the following primitive operations: Get a value (input: e.g. get value for radius) Print a value or message (output: e.g. print value of area or print the message “Hello”) Set the value of an object (e.g. set Pi to 3.14) Performs a computation and stores the result. set area to Pi × radius × radius Using arithmetic operations: e.g. +, -, ×, /. Satisfy priorities and using parenthesis. Step 1: get value for radius Step 2: set Pi to 3.14 Step 3: set area to Pi × radius × radius Step 4: print value of area CS111 Introduction to Computers By Dr. Khaled Wassif

17 Pseudo-Code: Not too Strict on Syntax
Pseudo-code is a kind of programming language without a rigid syntax. For example: We can write: set A to B+C as set value of A to B + C Or write: set A to 0 set B to 0 set A and B to 0 CS111 Introduction to Computers By Dr. Khaled Wassif

18 Operations of Algorithms
Algorithms can be constructed by the following operations: Sequential Operation Conditional Operation Iterative Operation CS111 Introduction to Computers By Dr. Khaled Wassif

19 Sequential Operations
Each step is performed in the order in which it is written. Example 1: Given the radius of circle, determine the area and circumference. Names for the objects: Input: radius Outputs: area, circumference Algorithm in Pseudo-code: get value for radius set area to (radius * radius * 3.14) print value of area set circumference to (2 * radius * 3.14) print value of circumference CS111 Introduction to Computers By Dr. Khaled Wassif

20 Sequential Operations (cont.)
Example 2: Algorithm for finding the average of three numbers. get value for A, B, C set Sum to A+B+C set Average to Sum/3 print value of Average Example 3: The distance between two points (x1; y1) and (x2; y2) can be calculated using the following equation: d = Write an algorithm that calculates the value of d. get value for x1, y1, x2, y2 set d to SQRT((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1)) print value of d 2 2 CS111 Introduction to Computers By Dr. Khaled Wassif

21 Sequential Operations (cont.)
Example 4: write an algorithm to convert temperature from Celsius to Fahrenheit using the following formula: Tf = 9/5 * Tc + 32 The algorithm: get value for Tc set Tf to 9/5 * Tc + 32 print the message “Temperature = ” print value of Tf print the message “ degrees Fahrenheit” CS111 Introduction to Computers By Dr. Khaled Wassif

22 Sequential Operations (cont.)
Example 5: Write an algorithm to determine the flying time between two cities given the distance between them and the average speed of the airplane. The algorithm: get value for distance, speed set time to distance / speed print the message “Flying time is ” print value of time CS111 Introduction to Computers By Dr. Khaled Wassif

23 Conditional Operations
Each operation is a control operations that allow us to alter the normal sequential flow of control in an algorithm. Let's say you are going out tomorrow. You need to make a decision on what to wear depending on the weather forecast. Therefore, your decision will be based on a certain condition: Is the weather going to be rainy? If the answer is yes then, wear the raincoat. If the answer is no then no raincoat is needed. CS111 Introduction to Computers By Dr. Khaled Wassif

24 Conditional Operations (cont.)
We can express the last situation using if-statement in the following manner: if (weather = "rainy") then print the message "Wear rain coat" else print the message "Do not wear rain coat" endif General format: if (condition) then statement(s) else if (condition) ... … … e1se Optional CS111 Introduction to Computers By Dr. Khaled Wassif

25 Boolean Expressions Comparisons Composite Expressions - Logical AND
Applied to two expressions of compatible type and always yield a boolean result: a < b (less than) a <= b (less than or equal) a = b (equals) a > b (greater than) a >= b (greater than or equal) A != b (not equal) Composite Expressions - Logical AND (X AND Y) yields true only if both X and Y evaluate to true. Composite Expressions - Logical OR (X OR Y) yields true if either X or Y, or both are true. CS111 Introduction to Computers By Dr. Khaled Wassif

26 Conditional Operation Examples
Heart rate is usually calculated as the number of heart beats in one minute and expressed as "beats per minute" (bpm). When resting, the adult human heart beats at about 70 bpm. Write an algorithm that gets heart rate as input and decide whether rate is normal or not. The algorithm: get value for Rate if (Rate = 70) then print the message "Normal Heart Rate" else print the message "Abnormal Heart Rate" endif CS111 Introduction to Computers By Dr. Khaled Wassif

27 Conditional Operation Examples
Write an algorithm that decides whether a given number is positive or negative. Inputs: number Output: Number sign The algorithm: get value for number if (number < 0) then print the message "The number is negative" else print the message "The number is positive" endif CS111 Introduction to Computers By Dr. Khaled Wassif

28 Conditional Operation Examples
Write an algorithm that inputs two numbers x and y, and computes and displays the division of x over y if the value of y is not zero. If y does have the value 0, then display the message "Unable to perform division". The algorithm: get value for x, y if (y = 0) then print the message " Unable to perform division" else set d to x/y print value of d endif CS111 Introduction to Computers By Dr. Khaled Wassif

29 Conditional Operation Examples
Write an algorithm that gets the temperature as input and decide whether the weather is cold, hot or nice based on the following criteria: Temperature > 30 Hot weather Temperature < 18 Cold weather Otherwise Nice weather Inputs: temperature (temp) Output: Weather state CS111 Introduction to Computers By Dr. Khaled Wassif

30 Conditional Operation Examples
The algorithm: get value for temp if (temp > 30) then print the message "Hot Weather" else if (temp 18) then print the message "Cold Weather" else print the message "Nice Weather" endif CS111 Introduction to Computers By Dr. Khaled Wassif

31 Conditional Operation Examples
Write an algorithm that gets the values of starting account balance, annual interest rate and annual service charge. The algorithm includes the annual service charge only if the starting account balance is less than 1,000 pounds at the beginning of the year. The algorithm should compute and display the balance after one year. The algorithm: get value for SB, IR, SC if (SB < 1000) then set EB to SB * (1 + IR) - SC else set EB to SB * (1 + IR) endif print value of EB CS111 Introduction to Computers By Dr. Khaled Wassif

32 Conditional Operation Examples
Write an algorithm that outputs the grade of the student according to the following rules: Grade "A" if 90 ≤ mark ≤ 100 Grade "B" if 80 ≤ mark ≤ 89 Grade "C" if 65 ≤ mark ≤ 79 Grade "D" if 50 ≤ mark ≤ 64 Grade "F" if mark < 50 Inputs: mark Output: grade CS111 Introduction to Computers By Dr. Khaled Wassif

33 Conditional Operation Examples
The algorithm: get value for mark if (mark >= 90) then set grade to “A” else if (mark >= 80) then set grade to “B” else if (mark >= 65) then set grade to “C” else if (mark >= 50) then set grade to “D” else set grade to “F” endif print value of grade CS111 Introduction to Computers By Dr. Khaled Wassif

34 Conditional Operation Examples
Write an algorithm that outputs the maximum of three numbers. The algorithm: get value for A, B, C if (A >= B) then if (A >= C) print value of A else print value of C endif if (B >= C) print value of B Or get value for A, B, C if (A >= B and A >= C) then print value of A else if (B >= A and B >= C) then print value of B else print value of C endif CS111 Introduction to Computers By Dr. Khaled Wassif

35 Iterative Operations Allow the repetition of a block of statements according to a condition. Example: Printing numbers from one to ten. Iteration is sometimes called looping. Common style of looping is using while statement. General format: while (condition) statement(s) endwhile The purpose of the while loop is to repeat a block of statements while the condition is true. CS111 Introduction to Computers By Dr. Khaled Wassif

36 Iterative Operation Examples
Write an algorithm to print numbers from one to ten. Loop: initial value: 1 final value: 10 step: 1 The algorithm: set num to 1 while (num <= 10) print value of num set num to num + 1 endwhile Initial value Final value Step CS111 Introduction to Computers By Dr. Khaled Wassif

37 Iterative Operation Examples
Modify the previous algorithm to print numbers from one to n. Loop: initial value: 1 final value: n step: 1 The algorithm: get value for n set num to 1 while (num <= n) print value of num set num to num + 1 endwhile CS111 Introduction to Computers By Dr. Khaled Wassif

38 Iterative Operation Examples
Write an algorithm to print sum of numbers from one to n. The algorithm: get value for n set sum to 0 set num to 1 while (num <= n) set sum to sum + num set num to num + 1 endwhile print value of sum CS111 Introduction to Computers By Dr. Khaled Wassif

39 Iterative Operation Examples
Write an algorithm to compute and print the factorial of n. The algorithm: get value for n set fact to 1 set num to n while (num >= 1) set fact to fact * num set num to num - 1 endwhile print value of fact CS111 Introduction to Computers By Dr. Khaled Wassif

40 Iterative Operation Examples
Write an algorithm that prints all the leap years from the year to the year A leap year is a one that is divisible by 4. The algorithm: set year to 1901 while (year <= 1999) if (year % 4 = 0) then print value of year endif set year to year + 1 endwhile CS111 Introduction to Computers By Dr. Khaled Wassif

41 Iterative Operation Examples
Given 800 kilograms of a radioactive substance that decreases in mass by half every year. Write an algorithm that calculates how many years it takes until it reaches a value of 25 kilograms. The algorithm: set mass to 800 set years to 0 while (mass > 25) set mass to mass/2 set years to years + 1 endwhile print value of years CS111 Introduction to Computers By Dr. Khaled Wassif

42 Iterative Operation Examples
Euclidean algorithm finds the greatest common divisor of two positive numbers X and Y by repeatedly replacing the larger number with the result of subtracting the smaller one from it until the two numbers become equal. Express this algorithm. The algorithm: get value for X, Y while (X != Y) if (X > Y) then set X to X - Y else set Y to Y – X endif endwhile print value of X CS111 Introduction to Computers By Dr. Khaled Wassif


Download ppt "Software and Algorithms"

Similar presentations


Ads by Google