Lab: Expressions

Please complete your work for today’s lab in a new directory: ~/csc161/labs/expressions. It would be a good idea to try to practice using the terminal to create directories, but you’re welcome to use the graphical file browser to confirm things are working as you expect.

A. Integer Calculations

Consider the following C program fragment:

int a = 5;
int b = 6;
int c = a / b;
int d = b / a;
int e = (a + b) / 10;
int f = (a + b) % 10;
printf("a=%d, b=%d, c=%d, d=%d, e=%d, f=%d\n", a, b, c, d, e, f);

Exercises

Driver: The student closer to the whiteboard.

  1. Write down your predictions about what the code fragment above will print (do not run the code yet). Include an explanation of why you predicted each output.
  2. Create a new C source file and paste the code fragment above into main(). You’re welcome to copy a source file from an earlier lab to start.
  3. Compile and run the program. Compare your predictions to the actual output. Wherever you were incorrect, try to explain what the computation did and how it differs from your prediction.

B. Operator Precedence and Associativity

Consider this C program fragment:

int g = 5 + 4 * 3 + 1;
int h = 50 / 4 * 10 / 2;
int i = 19 % 3 * 9 - 2;
printf("g=%d, h=%d, i=%d\n", g, h, i);

Exercises

Driver: The student farther from the whiteboard.

  1. Make a prediction about the values of g, h, and i in the program fragment above. Write your predictions down before moving on.
  2. Put this fragment into main() in a new C source file, compile the program, and run it. Record the actual outputs along with your predictions from step 1.
  3. Add parentheses to each expression to show how operator precedence is working; every operator should be parenthesized with its two operands (e.g. (1 + (2 * 3))). Run the program again to make sure your parentheses did not change the program’s output.

C. Increment, Decrement, and Assignment

Consider this C program fragment:

int j = 1;
int k = ++j;
int l = (k = j) * 4;
printf("j=%d, k=%d, l=%d\n", j, k, l);

j *= k;
k++;
l /= 4;
printf("j=%d, k=%d, l=%d\n", j, ++k, l++);

Exercises

Driver: The student closer to the whiteboard.

  1. Predict the values of j, k, and l at the first printf. Copy that part of the code fragment into a C source file, compile it, and run it to check your predictions.
  2. Predict the values of j, k, and l at the second printf. Copy the rest of the program fragment into your C source file, compile it, and run it again to check your predictions.
  3. Many C programmers have a difficult time remembering the difference between pre- and post-increment operators (++x and x++). Write a short explanation and try to come up with a good way to remember what each one does. You might find it helpful to write a short test C program to check their behavior.