Computers and Algorithms

Today's Topics:

What is a computer?


Question: Which part of a computer executes a program?

A. main memory
C. keyboard

What is programming?

Algorithm Example

 Write an algorithm to compute the sum of the first 100 positive integers.

1. Set sum to 0.
2. Set n to 1.
3. Repeat while n <= 100:
    3a. Set sum to sum + n.
    3b. Set n to n+1.
4. Print sum.

Convert this algorithm into Python:

       sum = 0
       n = 1

       # Add all integers from 1 to 100 to sum
       while n <= 100: # do this as long as n is at most 100
          sum = sum + n
          n = n+1
       print sum

Programming Languages

Algorithms: More Examples

               1. Initialize the sum to 0.
               2. If there are no numbers remaining, go to step 5.
               3. Add the next number to the sum.
               4. Go to step 2.
               5. Output the sum.

               Psuedocode for this algorithm:

               Set sum to 0
               while (more numbers remain) add next number to sum
                print the sum

Exercise: Write an algorithm that prints the numbers from 1 to 100. (You can use psuedocode).



Exercise: Write an algorithm that prints the sum of all the even numbers from 1 to 100.