Main Contents Page
CTEC1401 Programming in C
Quick Reference
Week 7: Selection
Week 8: Iteration
Week 9: Arrays
  1. Before the lab session read CFTTP Chapter 6 and study the solved exercises very carefully.

  2. Attempt the unsolved exercises 6.1 to 6.10 at the end of Chapter 6.

  3. timestable1

    Write a C program timestable1.c that

    1. prompts the user to enter an integer value;
    2. prints out a "times-table" for the given value. The table should of length 12. So, if the user entered the value 7 then the output should look like this (make sure the columns line up neatly with numbers right justified):
       1  x  7  =   7
       2  x  7  =  14
       3  x  7  =  21
       4  x  7  =  28
       5  x  7  =  35
       6  x  7  =  42
       7  x  7  =  49
       8  x  7  =  54
       9  x  7  =  63
      10  x  7  =  70
      11  x  7  =  77
      12  x  7  =  84
      
  4. variance

    Consider the following C program variance.c that calculates the variance of a set of numbers based on the formula

    variance(X) = Sum(xi2)/N - (Sum(xi) / N)2
    #include <stdio.h>
    
    int main()
    {
        int i, n;
        float x, sum, sumsq, mean, var;
        printf("How many values? ");
        scanf(" %i", &n);
        sum = sumsq = 0;
        i = 0;
        while (i < n) {
        	printf("Input next value (%i) --> ", i);
        	scanf(" %f", &x);
        	sum += x;
        	sumsq += x * x;
        	i++;
        }
        mean = sum / n;
        var = (sumsq / n) - (mean * mean);
        printf("Variance = %f\n", var);
        
        return 0;
    }
    

    Run the program and check that it works. Then modify the program so that instead of inputting the number of numbers (n) at the start of the program the user simply enters values until a negative value terminates the input sequence. Note that we are making the assumption here that we only want to input positive values which, in general, would not be the case - but we are adapting the problem for this exercise.

  5. charseq1

    Write a C program charseq1.c that

    1. prompts the user to enter a two values;
    2. prints out the sequence of characters between the two values (inclusive). So, for example, if the user entered the characters D then N then the output would be:
      D E F G H I J K L M N
      
      Note, if the user had entered the characters in the opposite order (N then D) the ouptut would be blank. This implies that the program is counting upwards from the first character.
  6. charseq2

    Write a C program charseq2.c that behaves like charseq1.c but with the added feature that the order in which the two characters are entered is not significant. Therefore, regardless of whether the higher or lower character is the first entered the sequence is still displayed in ascending order from the lowest to the highest.

  7. charseq3

    Write a C program charseq3.c that behaves like charseq1.c but with the following behaviour.

    1. If the first character entered is lower than the second then the sequence is printed out in ascending order (just the same behaviour as charseq1.c)
    2. If the first character entered is higher than the second then the sequence is printed in descending order.

  8. checkout

    Write a C program checkout.c that adds up numbers as they are typed in. This is rather like scanning prices at a supermarket checkout. The program should repeatedly input float values representing prices (in pounds and pence such as 3.25) and keep a running total

    When the user enters a zero price the program should stop reading numbers and print out (a) the grand total and (b) the number of items. For example:

    Price?   0.54
    Price?   2.23
    Price?   0.77
    Price?   1.99
    Price?   0.00
           ------
    Total:   5.53   (4 items)
    
  9. Supplementary Exercises

  10. highlow

    Using a while loop with a nested if statement, write a C program highlow.c that plays a guessing game. The user keeps entering a number and the program keeps responding by saying "Higher" or "Lower" until the user guesses the number correctly at which point the program should stop. For example, assuming the secret number was 22:

    Guess
          ? 8
    Higher
          ? 90
    Lower
          ? 40
    Lower
          ? 20
    Higher
          ? 30
    Lower
          ? 25
    Lower
          ? 22
          
    Correct - this took you 7 guesses.
    

    You will need to decide upon a secret number that the user must guess. This number will be part of your program. If you would like to choose this secret number randomly each time you run the program then you will need to use C's random number generator. Look up the functions rand and srand if you wish to do this.

  11. triangle1

    Create a text file called triangle1.c that contains the following C program:

    #include <stdio.h>
    
    int main()
    {
        int i, j, x;
        printf("How many units for the base of the triangle? ");
        scanf("%i", &x);
        i = 1;
        while (i <= x)
        {
            j = 1;
            while (j <= i)
            {
                printf ("*");
                j++;
            }
            printf("\n");
            i++;
        }
        return 0;
    }
    

    Notice how this program demonstrates one while loop nested inside another while loop. Control constructs in C (e.g. if statements, case statements, while loops, et.) are compound statements. The entire construct can be used wherever a statement is expected. This is a very powerful concept in structured programming.

    1. Save the file and then compile and run the program.
    2. Write a similar program called rectangle1.c that prints out a rectangle with length and width dimensions provided by the user.
  12. triangle2

    Write a C program triangle2.c that asks the user to enter an number representing the size of the base and then prints a reflected triangle. Refer to triangle1.c for inspiration if needed.

    The following output demonstrates the program as it should look in operation

    $ ./triangle2
    How many units for the base of the triangle? 20
                       *
                      **
                     ***
                    ****
                   *****
                  ******
                 *******
                ********
               *********
              **********
             ***********
            ************
           *************
          **************
         ***************
        ****************
       *****************
      ******************
     *******************
    ******************** 
    
  13. triangle3

    Write a C program triangle3.c that prints another reflected triangle. Refer to triangle2.c for inspiration if needed.

    The following output demonstrates the program as it should look in operation

    $ ./triangle3
    How many units for the base of the triangle? 20
    ********************
     *******************
      ******************
       *****************
        ****************
         ***************
          **************
           *************
            ************
             ***********
              **********
               *********
                ********
                 *******
                  ******
                   *****
                    ****
                     ***
                      **
                       *
    
  14. timestable2

    Write a C program timestable2.c that

    1. prompts the user to enter an integer value;
    2. prints out all the "times-tables" up to the given value. The tables should be of length 12. So, if the user entered the value 7 then the output should look like this (make sure the columns line up neatly with numbers right justified):
              1    2    3    4    5    6    7
           ----------------------------------
       1  |   1    2    3    4    5    6    7
       2  |   2    4    6    8   10   12   14
       3  |   3    6    9   12   15   18   21
       4  |   4    8   12   16   20   24   28
       5  |   5   10   15   20   25   30   35
       6  |   6   12   18   24   30   36   42
       7  |   7   14   21   28   35   42   49
       8  |   8   16   24   32   40   48   54
       9  |   9   18   27   36   45   54   63
      10  |  10   20   30   40   50   60   70
      11  |  11   22   33   44   55   66   77
      12  |  12   24   36   48   60   72   84
      
  15. calendar2

    Previously you wrote the programs leapyear.c that determines if a given year (≥ 1582) is a leap year. You also wrote weekday.c that determines the actual day of the week (sun / mon / etc.) for a given date.

    Write a C program calendar2.c that

    writes out a calendar for any month in the following format

                 Su Mo Tu We Th Fr Sa
                              1  2  3
                  4  5  6  7  8  9 10
                 11 12 13 14 15 16 17
                 18 19 20 21 22 23 24
                 25 26 27 28 29 30
    

    Note, you can compare your results with the Unix calendar program but note that it follows the adoption of the Gregorian Calendar in 1752 (in UK and North America) so the comparison will only be valid from October 1752. Have a look at the Unix calendar
    cal 1752
    
    for that year and look at September.