Main Contents Page
CTEC1401 Programming in C
Quick Reference
Week 3: Types, Vars, Output
Week 4: Input with scanf()
Week 5: Operators
  1. Before the lab session read CFTTP Chapter 3 and study the solved exercises very carefully.

  2. Attempt the unsolved exercises 3.1 to 3.4 at the end of Chapter 3.

  3. varz

    Create a text file called varz.c that contains the following C program:
    #include <stdio.h>
    
    int main()
    {
        int z;
        printf("Input the value of z ");
        scanf(" %i", &z);
        printf("   1 x %4i = %8i\n", z, z);
        printf("  10 x %4i = %8i\n", z, 10*z);
        printf(" 100 x %4i = %8i\n", z, 100*z);
        printf("1000 x %4i = %8i\n", z, 1000*z);
        return 0;
    }
    

    1. Compile and run the program.
    2. Modify the program so that it inputs two numbers from the keyboard and prints out the sum of the numbers, the product of the numbers, the difference of the numbers, the sum of the squares of the numbers. The print messages should describe the output values appropriately.

  4. oppo1

    Write a program called oppo1.c that inputs ten integer values from the keyboard and then prints them out, one line at a time, in the reverse order to that in which they were entered.
  5. oppo2

    Write a program called oppo2.c that inputs ten character values from the keyboard and then prints them out, one line at a time, in the reverse order to that in which they were entered.
  6. inxoutx

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

    #include <stdio.h>
    
    int main()
    {
      int x;
      printf("Enter a value for x ? ");
      scanf("%i", &x);
      printf ("You entered %i\n", x);
      return 0;
    }
    

    Save the file and then compile and run the program. (Run it a number of times trying different input values.)

  7. inxyoutxy

    Write, compile and run a C program, inxyoutxy.c, which declares two integers x and y and inputs their values from the keyboard. Refer to inxoutx for inspiration. Then your program should output the values of x and y.

  8. speed

    The final speed of a car accelerating from an intial speed for a specified time is given by the formula:

    final = initial + acceleration * time

    Write, compile and run a C program, speed.c, which

    • declares four int variables called final, initial, acceleration, and time;
    • prompts the user to enter values for initial, acceleration, and time and reads them in;
    • calculates the final speed according to the formula above;
    • prints out the final speed.
  9. sumToN

    The sum of the numbers from 1 up to N is given by the formula:

    sum = N * (N + 1) / 2

    Write, compile and run a C program, sumToN.c, which

    • declares int variables called N, and sum;
    • prompts the user to enter a values for N and inputs it;
    • calculates the sum according to the formula above;
    • prints out the result. NB: The way the output should look is given below (the example assumes that the user entered a value of 10 for N).

      The sum from 1 to 10 is 55.

  10. sumSqToN

    The sum of the squares of the numbers from 1 up to N is given by the formula:

    sumsq = N * (N + 1) * (2 * N + 1) / 6

    Thus, if N=4, then 12 + 22 + 32 +42 = 4 x 5 x 9 / 6 = 30

    Write, compile and run a C program, sumSqToN.c, which

    • declares int variables called N, and sumsq;
    • prompts the user to enter a values for N and inputs it;
    • calculates the sum of the first N squares (sumsq) according to the formula above;
    • prints out the result (nicely).
  11. sumCubesToN

    The sum of the cubes of the numbers 1 to N is given by the formula:

    sumcubes = N2 * (N + 1)2 / 4

    This 13 + 23 + 33 + 43 = 42 x 52 / 4 = 100

    Write, compile and run a C program, sumCubesToN.c, which

    • declares int variables called N, and sumcubes;
    • prompts the user to enter a values for N and inputs it;
    • calculates the sum of the first N cubes (sumcubes) according to the formula above;
    • prints out the result (nicely).
  12. circle

    The area and circumference of a circle is given by the formulae:

    area = pi * radius * radius

    circumference = 2 * pi * radius

    Write, compile and run a C program, circle.c, which

    • declares four float variables called pi, radius, area, and circumference;
    • initialises the value of pi correct to eight decimal places;
    • prompts the user to enter a values for radius and inputs it;
    • calculates the area and the circumference according to the formulae above;
    • prints out the results. Use printf formatting and make the output look neat, tidy and informative.
  13. cinema

    Suppose the price for a standard cinema ticket is $20 and a child's ticket is $10. Write, compile and run a C program, cinema.c, which inputs the number of adults and the number of children wishing to purchase tickets and then outputs the total cost.

    Hint: Declare two int variables for storing the number of adults and children respectively.

  14. Supplementary Exercises

  15. intersect

    A straight line can be defined by an equation that relates y-axis values to x-axis values. Traditionally it is written like this: y = m x + c where m is the gradient of the line and c is the point at which the line crosses the y-axis. Here are two examples:

        y
        ^         y=2x+1     If we want to know where the lines
     \  |       /            cross then we fix their y values to
      \ |      /             be equal and solve for x.
       \|     /              
        \    /               E.g.:       2x+1 = -2x+6
        |\  /                         2x+2x+1 = 6     {add 2x}
        | \/                          2x+2x   = 5     {subtract 1}
        | /\                          4x      = 5     {collect}
        |/  \                          x      = 5/4   {divide by 4}
        /    \                
    ---/|-----\------> x     ∴ lines meet when x = 1.25
      / |      \                
     /  |       \y=-2x+6    
    

    If you are intereseted in how to derive the formula for calculating the intersection of two lines then it is explained here. However, you can skip this if you don't want to follow the maths and jump to the specification of the exercise below. You don't need to understand the mathematical derivation in order to write the function that uses it.

    In general, if we have two lines defined by the equations: y = m1x + c1 and y = m2x + c2 then we can work out the x-coordinate of the point at which the lines cross by equating their y values and solving the resulting equation:

    m1x + c1 = m2x + c2
    m1x - m2x + c1 = c2
    m1x - m2x = c2 - c1
    (m1 - m2)x = c2 - c1
    x = (c2 - c1) / (m1 - m2)

    Exercise Specification

    Write a program intersect.c that

    1. Defines four floating point values used to describe two straight lines:
      m1 and c1
      m2 and c2
    2. Prompts the user to enter these values.
    3. Calculates the x-coordinate of the point at which the two lines cross.
    4. Prints out the (x,y) coordinates of the point at which their lines intersect.

    You can test your program with combinations of the following lines (and some others of your own).

    y = x
    y = -x
    y = 0.5x + 2
    y = 2x + 1
    y = -2x + 6
    y = -4

  16. calcprice

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

    #include <stdio.h>
    
    int main()
    {
        float initialPrice, discount, VAT, priceWithVAT, priceWithDiscount;
        initialPrice = 13.26;
        VAT          = 0.20;
        discount     = 0.125;
        
        priceWithVAT      = initialPrice * (1.0 + VAT);
        priceWithDiscount = priceWithVAT * (1.0 - discount);
            
        printf("Initial Price      %10.2f\n", initialPrice);
        printf(" + VAT @ %4.1f%%     %10.2f\n", VAT*100,      priceWithVAT);
        printf(" - discount @ %4.1f%%%10.2f\n", discount*100, priceWithDiscount);
        return 0;
    }
    
    1. Save the file and then compile and run the program.
    2. Then modify the program so that it uses scanf to read in the initial price before doing the calculations.
  17. roots

    The two roots of the quadratic equation   a x2 + b x + c = 0   are given by the formulae:

    r1 = ( − b + √(b2 − 4 a c) )  /  (2 a)

    r2 = ( − b − √(b2 − 4 a c) )  /  (2 a)

    Write, compile and run a C program, roots.c, that

    1. declares float variables a, b, and c;
    2. prompts the user to enter values for the three variables;
    3. calculates both roots according to the formulae above;
    4. prints out the results.
    You need to test this program carefully. To get any sensible values you will need to ensure that b2 ≥ 4 a c.   Why is this?
  18. caesar

    A Caesar Cipher (or Cipher Wheel) is an ancient mechanism for encrypting text and a popular children's toy. It encrypts a message by shifting each alphabetic character in the text by a fixed amount. For example, a Caesar cipher with a shift of 4 translates a to e, b to f etc.

                abcdefghijklmnopqrstuvwxyz
                efghijklmnopqrstuvwxyzabcd  
    
    and would encrypt helloworld as lippsasvph

    Write a program caesar.c that

    1. declares a char variable which defines the character to be encrypted;
    2. declares an int variable which defines the amount to be shifted;
    3. assigns a lower case value to the character and an integer value to the shift;
    4. prints out the original character and its "shifted" value.

    Test your program with various values for the character and the shift, remembering to test "boundary" values like a character value of 'z' and a shift of 0.

    Hint: There are only 26 characters so your shift may have to roll around (e.g. 'w' shifted by 4 rolls around to 'a'. You might like to look at the modulus operator % as a way of solving this.)

  19. carpet

    Consider a (potentially large commercial) room that has floor dimensions length len and width wid. The area of the floor is given by multiplying len by wid.

    Carpet tiles are provided as individual squares (2 feet by 2 feet). Write, compile and run a C program, carpet.c, that

    1. calculates the minimum number of carpet tiles that are needed to cover a room whose dimensions (len and wid) are input from the terminal (measurements are in inches). NB: floor tiles can be cut to fit at the edges of the room - try to minimise waste.
    2. calculates how many carpet-tile packs are needed. The supplier only provides carpet tiles in packs of ten (i.e. individual tiles cannot be purchased separately).
    3. calculates how many spare tiles are left over once the minimum number of packs have been purchased.
    4. prints out all these results in a neat table along with the total cost of the order. (A pack of tiles costs $50 for each of the first four packs, and the price reduces to $45 for each subsequent pack.)

    Think carefully about how are you going to test your program? The calculations are non-trivial and easy to get wrong. If your program doesn't work then you will waste the company a lot of money and you will probably lose the contract to supply the software.

    You should write out a number of test cases (by hand) that cover all the different possibilities that could happen. Don't forget to consider various boundary cases too - these are often where errors are detected.

  20. andTT, orTT, nandTT, norTT

    The C Programming Language does not have a Boolean data type. Instead, it uses int values to represent truth values. Zero (0) is used to represent false. Any other value is interpreted as true. It is normal for the value one (1) to be used when generating a value to represent true.

    In this example we have used the int variables f and t to represent the truth values (false (0) and true (1) repectively). The Truth Table shows the result of applying the logical-and operator to every combination of truth values. There are four combinations which is why the truth table has four rows.

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

    #include <stdio.h>
    
    int main()
    {
        int f = 0;
        int t = 1;
        printf("x\ty\tx&&y\n");
        printf("%i\t%i\t%i\n", f, f, f && f);
        printf("%i\t%i\t%i\n", f, t, f && t);
        printf("%i\t%i\t%i\n", t, f, t && f);
        printf("%i\t%i\t%i\n", t, t, t && t);
        return 0;
    }
    
    1. Save the file and then compile and run the program.
    2. Write three similar programs (orTT.c, nandTT.c, norTT.c) that print the truth tables for three more logical operators: or, nand, nor.

      C uses the built-in operator || for the logical operation or.

      A logical nand operation needs to be simulated by negating the result of an and operation.

      A logical nor operation needs to be simulated by negating the result of an or operation.

      In C the built-in operator ! is used for logical-not.