Introduction to Algorithms Yonglei Tao What is an Algorithm? A step-by-step description about a solution to a problem Unambiguous In a logical order Executable A program is the expression of an algorithm in a programming language Examples of Algorithm Making a phone call 1) 2) 3) 4) 5) 6) Pick up the receiver Hear the dial-tone Dial a phone number Wait for the reply Talk Replace the receiver Other examples Programming a VCR A recipe for a cake Building Instructions for LEGO Developing an Algorithm How to develop an algorithm? Problem solving How to describe an algorithm? In English? In a programming language? Pseudocode English statements + basic control structures in programming languages Good compromise Simple, readable, no strict rules, don’t worry about punctuation Let you think at an abstract level about the problem Allow you to focus on what needs to be done without having to deal with the syntax and grammar of a programming language Pseudocode vs. Code Pseudocode Get the rate from user VB code dblRate = Convert.ToDouble(txtRate.Text) Building Blocks for Pseudocode Basic statements Get the input (from user) Print the output (on the screen) Perform basic calculations Conditional and iterative statements Variables Variables How to do (2 + 3) * (5 – 1) using a calculator? A variable is a memory location Can store a value Addressable by its name Examples count sum Basic Statements Assign values to variables using basic arithmetic operations Get input from user Set the value of x to 3 or x = 3 Set the value of y to x/10 or y = x/10 Set the value of z to x +25 or z = x + 25 Get the value of x Print results to the screen Print the value of y, z Print “CIS160 Visual BASIC” Example Write pseudocode that asks the user for three numbers, computes their sum and average and outputs the results. 1. 2. 3. 4. Get the values of a, b, c from user avg = ( a + b + c ) / 3 sum = a + b + c Print sum, avg Example Write pseudocode that reads the value of a circle radius from the user, and prints the area of a circle with that radius 1. 2. 3. Get the value of radius from user area = pi * radius * radius Print “The area of your circle is “ & area Exercise Write pseudocode that inputs the length and width of a carpet in feet and the price in dollar per square yard. The algorithm should print out the total cost of the carpet, including a 6% sales tax. 1 square yard = 9 square feet