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

  2. Attempt the unsolved exercises 4.1 to 4.5 at the end of Chapter 4.

  3. iplusj

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

    #include <stdio.h>
    
    int main()
    {
        int i, j, k;
        i = 10;
        j = 20;
        k = i + j;    
        printf("i   = %i\n", i);
        printf("j   = %i\n", j);
        printf("k   = %i\n", k);
        printf("i+j = %i\n", i+j);
        return 0;
    }
    
    1. Save the file and then compile and run the program.
    2. Then modify the program so that instead of "hard-coding" initial values for the variables i and j, the user is prompted to enter their intial values instead. (Run your modified program using a variety of different input test values.)
  4. iplusjtimesk

    Write, compile and run a C program, iplusjtimesk.c, which asks the user to enter three integer values i, j and k and prints out the (different) values of i + j * k.

    1. Run the program and enter the value 2 for i, 3 for j and 4 for k. What answer do you get?
    2. Modify your program (by introducing some brackets into the calculation) so that it gives the answer 20 for these input values.

    Expressions are usually evaluated left to right, but operators have different precedences, which means, e.g., that * is evaluated before +. When you have multiple operations in the same expression, it is generally worth using more brackets than strictly necessary to make the order of calculation clear.

    Arithmetic Operators
    operator action example expression
    result
    int u = 17, v = 7, w = -2;
    - unary minus -u
    -w
    -17
    2
    + addition u + v
    u + v + w
    24
    22
    - subtraction u - v
    u - v - w
    10
    12
    * multiplication u * v
    u * v * w
    119
    -238
    / (integer) division u / v
    v / w
    2
    -4
    % modulus u % v
    v % w
    3
    -1

  5. reltab1

    The relational operators in C are used for comparing values in the sense of greater-than, less-than, eaual-to, etc. The quantities being compared must be comparable and this includes all the basic C types (which are all essentially numeric - including char).

    The symbols used are < (less-than), > (greater-than), <= (less-than-or-equal-to), >= (greater-than-or-equal-to), == (equal-to), != (not-equal-to).

    Write a program reltab1.c that

    1. Prompts the user to enter two int values;
    2. Prints a table showing the result of comparing the two values using each of the six relational operators. The table will have six rows. For example, if the user typed in 4 and 7 then the output would be:
          4  <  7 is 1
          4  >  7 is 0
          4  <= 7 is 1
          4  >= 7 is 0
          4  == 7 is 0
          4  != 7 is 1
          

      Remember that the result of a relational operator will be zero (false) or one (true).

    Make sure you run the program with a variety of inputs that thoroughly checks all of the operators. (Think about special cases.)

  6. reltab2

    Copy your program reltab1.c into a new file called reltab2.c. Now edit reltab2.c so that the values being input and compared are of type char (instead of int). Compile, run and test your program thoroughly.

  7. Supplementary Exercises

  8. ademo

    The following program is not designed to be pretty - but it does a job. (We certainly don't expect you to follow how it works at this stage although you are free to inspect it of course.) However, if you save this program as ademo.c and compiile it as ademo then you can use it as an experimental workbench for working with simple expressions. In particular, it will allow you to try out various C operators and see how they behave.

    The program sets up four integer variables (a, b, c, and d) initialised to zero. It then enters an interactive (command-line) mode in which you can type in a C statement to update the variables and then observe the results. Please note, this program has only been designed to work for straightforward assignment statements to the given variables -- anything it can't understand will simply result in an error which it will ignore. The commands it recognises are

    set(p,q,r,s)
    Sets (a,b,c,d) directly to the values (p,q,r,s) respectively. For example:
    set(0,0,0,0)
    to initialise all four variables to zero.
    assignment statement(s)
    Updates the variables. For example:
            a = b + c
    b = c % b + (a - b)
    c = a < b
    d = c++ * (b && a)
    a++; b = c++
    etc.
    undo
    Undoes the last experiment - returning the variables to their previous state.
    quit
    Stops the program.

    Note: Don't spend too long playing with this demo program now. Try some examples and then keep it somewhere safe so that you can experiment with it whenever you want.

    #include <stdio.h>
    #include <string.h>
    
    /* Author: drs
     * C program to allow interactive experimentation with assignment statements
     * Note: this is only a demo program - it does not catch division by zero errors
     * and it does not parse arbitrarily complex C expressions.  Its purpose is to
     * allow the entering and editing of simple C assignment expressions based on
     * four integer variables: a, b, c and d.
     * Usage:
     *        Save this program as: ademo.c
     *        Compilie:             gcc ademo.c -o ademo
     *        Run:                  ./ademo
     *             This will use the local files:
     *                      __default__program.c  (which it will create)
     *                      a.out
     *             You can change the name of the C program source by providing a
     *             command line argument (e.g. to use a file called "foo.c":
     *        Run:                  ./ademo foo.c
     *
     *        You can enter expressions such as:
     *        set(1,4,7,9)
     *        quit
     *        a = b + c
     *        d++
     *        c = a++ - b
     *        undo
     */
    
    #define MAX_LINES 100
    #define MAX_CHARS  40
    #define CMD_WIDTH  80
    #define DEFAULT_PROGRAM "__default__program.c"
    
    #define BEFORE "#include <stdio.h>\n\
    int a=0,b=0,c=0,d=0;\n\
    void show(int n, char* s)\
    {printf(\"%3d.      %-24s%10d%10d%10d%10d\\n\",n,s,a,b,c,d);}\n\
    void init(){a=0,b=0,c=0,d=0;}\n\
    void set(int w, int x, int y, int z){a=w;b=x;c=y;d=z;}\n\
    int main(void)\n{\nint n = 0;\n\
    printf(\" No.      %-24s%10s%10s%10s%10s\\n\",\"Expression\",\"a\",\"b\",\"c\",\"d\");\n"
    
    #define AFTER "return 0;\n}\n"
    
    int main(int argc, char** argv) 
    {
       char a[MAX_LINES][MAX_CHARS];
       int i, n = 0, undo = 0;
       FILE * f;
       char compile[CMD_WIDTH];
       char program[CMD_WIDTH];
       char command[MAX_CHARS];
    
       if (argc>1) 
           strcpy(program,argv[1]);
       else
           strcpy(program,DEFAULT_PROGRAM);
    
       printf("Using program file %s\n", program);
       compile[0] = '\0';
       strcpy(compile,strcat(strcat(compile,"gcc "),program));
    
       while (n<MAX_LINES) {
    
          f = fopen(program,"w");
          fprintf(f,"%s",BEFORE);
          for (i=0; i<n; i++)
              fprintf(f,"%s; show(++n,\"%s\");\n",a[i],a[i]);
          fprintf(f,"%s",AFTER);
          fclose(f);
    
          if(system(compile) == 0)
             system("./a.out");
          else {
              if (n>0) n--;
          }
    
          printf("(%2i)Expr? ",n+1);
          fgets(command,MAX_CHARS,stdin);
          command[strlen(command)-1] = 0;
    
          if      (strncmp(command,"undo",4) == 0) {
              undo = 1;
          }
          else if (strncmp(command,"quit",4) == 0) {
              printf("stopping...\n");break;
          }
    
          if (undo) {
              if (n>0) n--;
              undo = 0;
              printf("Undone\n");
          }
          else {
              strcpy(a[n],command);
              n++;
          }
    
       }
       return 0;
    }
    

  9. char2bin

    printf() allows you to print the value of variables in various formats. However it does not have a binary format.

    Write a program char2bin.c which

    1. declares an unsigned char variable
    2. reads a value into this variable (from the keyboard)
    3. prints out the 8-bit binary representation of this value e.g. 99 will print as 01100011

    Hint: This is all about powers of 2.

    (You don't need loops to do this, but if you know how to use them already then feel free to do so - the code will be simpler.)