Increment and Decrement Operators Quiz Quiz

Enhance your understanding of increment and decrement operators in programming with this quiz. Evaluate your ability to predict outcomes, recognize operator placement effects, and avoid common pitfalls involving these fundamental operators.

  1. Post-increment Evaluation

    Given: int x = 5; int y = x++; What is the final value of y after these statements execute?

    1. 6
    2. 0
    3. 4
    4. 5

    Explanation: The post-increment operator (x++) increases x after its current value is used in the expression. Thus, y is assigned the current value of x, which is 5, before x becomes 6. Option '6' is incorrect because it represents the post-incremented value, not what y receives. Options '0' and '4' are not relevant to the scenario, as the variables’ values never reach those numbers.

  2. Pre-decrement Operator Use

    If variable n is initialized as n = 10, what is the result of --n?

    1. 8
    2. 9
    3. 10
    4. 11

    Explanation: The pre-decrement operator (--n) decreases n by 1 before returning its value, so the result is 9. Option '10' is incorrect, as that would be n's value before the operation. Option '11' is an increase, not a decrease. Option '8' is too low; only a single decrement is performed.

  3. Effect on Sequences

    Consider int a = 7; int b = ++a; What is the value of both a and b after execution?

    1. a = 7, b = 8
    2. a = 7, b = 7
    3. a = 8, b = 7
    4. a = 8, b = 8

    Explanation: With the pre-increment operator (++a), a increases to 8 before being assigned to b. Therefore, both a and b become 8. Option 'a = 7, b = 8' is wrong because the increment happens first. Option 'a = 7, b = 7' ignores the increment. Option 'a = 8, b = 7' mistakenly applies the increment only to a, not taking pre-increment behavior into account.

  4. Complex Expression Outcome

    Given int x = 2; int y = x++ + ++x; What is the value of y?

    1. 3
    2. 5
    3. 4
    4. 6

    Explanation: First, x++ is 2 (x becomes 3 after), then ++x makes x 4, which is used as 4. Thus, y = 2 + 4 = 6. Option '5' incorrectly adds 2 + 3 by misapplying when x is incremented. Option '4' does not add the correct operands, and '3' ignores both increments.

  5. Operator Placement Impact

    In which scenario does the post-decrement operator return the original value before decreasing the variable?

    1. When using '--value' in a function call
    2. When using 'value--' in an assignment
    3. When using '--value' in a calculation
    4. When simply declaring the variable

    Explanation: The post-decrement operator (value--) returns the original value before reducing it by one, particularly visible in assignments or expressions. Using '--value' applies the decrement before the value is returned, so it's not the same. Option 'when simply declaring the variable' does not involve any operator. Option 'when using --value in a function call' describes pre-decrement, not post-decrement.