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

  2. Attempt the unsolved exercises at the end of Chapter 2.

  3. varx

    Create a text file called varx.c that contains the following C program:
    #include <stdio.h>
    
    int main()
    {
        int x = 3;
        printf ("The value of x is %i\n", x);
        return 0;
    }
    

    1. Compile and run the program.
    2. Change the message so that it prints out the value of x first (e.g. "3, this is the value of x").
      Re-compile and re-run the program.

  4. varxy

    Copy program varx.c to a new file called varxy.c.

    1. Add another variable y whose initial value is 7.
    2. Change the message so that it prints out the values of both x and y using some suitable message.
      Re-compile and re-run the program.

  5. sumxy

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

    #include <stdio.h>
    
    int main()
    {
        int x = 7;
        int y = 3;
        printf ("%i + %i = %i\n", x, y, x+y);
        return 0;
    }
    
    Save the file and then compile and run the program.
  6. prodxy

    Write, compile and run a C program, prodxy.c, which declares two integers x and y initialised to the values 5 and 8 respectively, and then prints out their individual values followed by their product. (The output should be in the same style as the previous program sumxy).

  7. Supplementary Exercises

  8. sizeoftypes

    Each variable occupies a location in memory whose size is dependent on its type. You can find out both these values

    & and sizeof()
    &myVar produces an integer which is the start address of the variable named myVar, e.g.
    printf("variable X lives at %d\n",&X);
    sizeof(myVar) produces an integer which is the number of bytes occupied by the variable named myVar, e.g.
    printf("variable X is %d bytes long\n",sizeof(X));

    Write a program sizeoftypes.c which declares the following variables

             Type          Name        Initial Value
             
             Integer       X1          44
             Short         I1          5
             Character     C1          'a'
             Integer       X2          no value
             Character     C2          no value
             Long          X3          12345 
    
    and prints out their name, value, start address and size in memory in a table of the form
                name      value    location    size
    
                X1        ????     ?????       ???
    
                I1        etc...   
    
    Compile and run sizeoftypes

    What do you notice about how the variables are stored in memory?

    What values do X2 and C2 have? Are you sure?

    Assign the value 373 to variable C1 and repeat the compilation and execution. What happens and why?