Cayuga Community College

Programming in C
Pop Quiz - Increment and Decrement operators

Answers

For questions 1 through 2, assume the following code:

int a;
int b;

a=1;

b=a++;

  1. What value does the variable b have after ALL of the code above executes?
    1. 1   ANSWER
    2. 2
    3. 3
    4. unknown/undefined

    Explanation: a++ is a post increment, so the increment happens after the value of the expression is determined. The value of the expression a++ is the current value of a, which is 1. So the value 1 is assigned to b, and therefore, the correct answer is 1.

  2. What value does the variable a have after ALL of the code above executes?
    1. 1
    2. 2   ANSWER
    3. 3
    4. unknown/undefined

    Explanation: a++ is a post increment, so the increment happens after the value of the expression is determined. a's value was 1, and after the increment, it is 2. Therefore, the correct answer is 2.

For questions 3 through 5, assume the following code:

int x;
int y;
int z;

x=3;
y=4;

z = ++x * y++;

  1. What value does the variable z have after ALL of the code above executes?
    1. 9
    2. 12
    3. 16   ANSWER
    4. 20

    Explanation: We must determine the values being multiplied together in the statement z=++x * y++;

    Dealing with the left operand of the multiplication operator, the expression is ++x. This is a pre increment, so we increment x before determining the result of the expression. So x is incremented to 4, and this new value of x is used as the left operand of the multiplication operator.

    Dealing with the right operand of the multiplication operator, the expression is y++. This is a post increment, so we determine the result of the expression before performing the increment. The present value of y is 4, so that value is used as the right operand of the multiplication operator.

    So the expression is evaluated as z=4 * 4. Therefore the answer is 16.

  2. What value does the variable x have after ALL of the code above executes?
    1. 2
    2. 3
    3. 4   ANSWER
    4. unknown/undefined

    Explanation: ++x is a pre increment, so the value of a x does get incremented. Therefore, the answer is 4.

  3. What value does the variable y have after ALL of the code above executes?
    1. 4
    2. 5   ANSWER
    3. 6
    4. unknown/undefined

    Explanation: y++ is a post increment, so the value of y does get incremented. Therefore, the answer is 5.

Return to the CS 222 Home Page.
Return to David's Home Page.
Return to Cayuga's Home Page.

Valid HTML 3.2!