COMP 1917 Computing 1
Session 2, 2016

Lab - Week 3

Loops


Instructions

  1. Create a directory called lab3 and cd to this directory.

  2. Write a program called sumk.c which, for each number k from 1 to 15, prints the sum of the numbers from 1 to k. Compile it to produce an executable called sumk. Your program should print a table in this format:
      1    1
      2    3
      3    6
      4   10
       etc.
    
    Note: you might like to use a format such as "%4d" in your printf() statement, to force the sums to be right-justified.

  3. Copy sumk.c to a new file sumcube.c . Modify the new file so that, for each integer k between 1 and 15, it prints the sum of the cubes of the numbers between 1 and k. Compile this program to produce an executable called sumcube. Note: you should change the number of digits in the format statement so the numbers remain right-justified.

    Food for Thought: Compare the output of sumk and sumcube. Do you notice any relationship between the numbers?

  4. A number is called "perfect" if it is equal to the sum of its factors other than itself. For example, 6 is a perfect number because it is equal to 1+2+3.
    Write a program perfect.c that reads a positive integer n from standard input and prints all the factors of n, along with their sum (excluding n itself) and then indicates whether n is a perfect number:
    % ./perfect
    Enter number: 6
    The factors of 6 are:
    1
    2
    3
    6
    Sum of factors = 6
    6 is a perfect number.
    ./perfect
    Enter number: 1001
    The factors of 1001 are:
    1
    7
    11
    13
    77
    91
    143
    1001
    Sum of factors = 343
    1001 is not a perfect number.
    
  5. Bonus Challenge (if time permits).
    Write a program prime_factors.c that reads an integer n from standard input and prints the decomposition of n into prime factors. If n is prime it should instead print a message indicating this:
    % ./prime_factors
    Enter number: 2048
    2048 = 2*2*2*2*2*2*2*2*2*2*2
    % ./prime_factors
    Enter number: 22500
    22500 = 2*2 * 3*3 * 5*5*5*5
    % ./prime_factors
    Enter number: 22501
    22501 is prime
    

  6. Show your work to your tutor, and submit it by typing
         give cs1917 lab3 *.c