CS 140
More practice problems on Functions

Here are some additional practice programming problems using loops and functions.

These are not to be handed in, though you should feel free to ask questions about any of them outside of class. Remember that programming is an activity that you learn by doing.

  1. Write a function TimesTable(n) that prints 1xn, 2xn, and so forth up to 12xn. For example, if n is 6 this should print
    1x6 = 6
    2x6=12
    3x6=18
    ...
    12x6=72
    Your main function should call TimesTable() 12 times, with the values 1 through 12 to get a complete set of times tables.
  2. Write a program that reads a list of numbers. This list stops when the user enters a value of 0. At that point you should print the sum of the list.
  3. Now change the program in (2), so that when you read the numbers you append them to a list. After you have finished with the input, have a loop that runs through the list summing the entries.
  4. Now change the program in (3) so that you have a function ReadNums(list) that builds up the list of numbers, and a function sum(list) that returns the sum of the numbers in the list.
  5. Either use the program in (4) or else write a new program that has a function ReadNums(list) that reads a list of numbers. Write another function PrintStars(list) that takes a list of numbers and prints one line for each number in the list, the line consisting of that many star (*) characters. For example, with the list [3, 1, 5] your PrintStars function will print
       ***
       *
       *****
  6. Write a program whose main() function has a loop that reads lines of text until it gets a blank line. For each non-blank line of text it gets it should print the length of the line.
  7. Change the program in (6) so that the program calls a fucntion spaces(line) that returns the number of blank spaces in the line. So instead of saying
         print len(line)
    you will say
         print spaces(line)
    Of course, you need to write the spaces(line) function.
  8. Write a program that reads lines of text and prints the reversal of each line. For this you need to write a function reverse(string) that returns the string in reverse order. Look at HW3 for suggestions on how to do this.