ANSWERS TO C EXPRESSION EXERCISES



 1. The statement "x = y;" replaces the value stored in variable
    x with the value stored in y. The statement "y = x;" replaces
    the value stored in y with the one in x.

    The "=" symbol in C means replace the variable on the left
    with the expression on the right. Do not confuse it with
    traditional mathematical equality.


 2. Exchanges the values stored in x and y.

 3. 
      A. No keyword "then" in C.
      B. Always need parentheses around the conditional.
      C. Nothing wrong.  This one is OK.
      D. Missing semicolon before "else".

 4.        #include <stdio.h>
           int main(void) {
              int a, b, c;
              scanf("%d %d %d", &a, &b, &c);
              if ((a == b) && (a == c))
                 printf("equal\n");
              else
                 printf("not equal\n");
              return 0;
           }


 5.        #include <stdio.h>
           int main(void) {
              int year;
              scanf("%d", &year);
              if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
                 printf("%d is a leap year\n", year);
              else
                 printf("%d is NOT a leap year\n", year);
              return 0;
           }


 6.  6 * 9 = 42
     Trick question.  #define is used to exactly substitute one sequence of
     characters with another.  Thus, SIX * NINE is replaced by 1 + 5 * 8 + 1.
     Since multiplication has a higher precedence than addition, this is
     parsed as 1 + (5 * 8) + 1.

     Lesson: #define is useful to avoid "magic numbers" or "hardwired constants",
     but don't get carried away.