C++ loop with pre-incremented counter and default parameters: what value does PowerFinder::Power print for (2, 6)?\n\n#include<iostream.h>\nclass PowerFinder\n{\npublic:\n void Power(int x = 1, int y = 1)\n {\n int P = 1, i = 1;\n while (++i <= y)\n {\n P *= x;\n }\n cout << P << endl;\n }\n};\nint main()\n{\n PowerFinder FP;\n FP.Power(2, 6);\n return 0;\n}

Difficulty: Easy

Correct Answer: 32

Explanation:


Introduction / Context:
The task is to evaluate a loop that multiplies an accumulator by the base x while a counter, pre-incremented each iteration, remains ≤ y. The nuance is the pre-increment ++i, which starts the loop with i = 2 on the first test when i is initialized to 1.


Given Data / Assumptions:

  • x = 2, y = 6.
  • Accumulator P starts at 1; i starts at 1.
  • Loop body: multiply P by x for each successful test of (++i <= y).


Concept / Approach:
Because the test uses ++i, the loop executes for i values 2, 3, 4, 5, and 6—five iterations. Multiplying 2 five times yields 2^5 = 32. There is no off-by-one on the upper bound because the comparison is ≤ y.


Step-by-Step Solution:
Iteration 1: i becomes 2 (≤ 6) → P = 1 * 2 = 2. Iteration 2: i = 3 (≤ 6) → P = 4. Iteration 3: i = 4 (≤ 6) → P = 8. Iteration 4: i = 5 (≤ 6) → P = 16. Iteration 5: i = 6 (≤ 6) → P = 32. Next test: i becomes 7 (> 6) → stop; print 32.


Verification / Alternative check:
Switch to i++ < y and you would also get five multiplications for these values.


Why Other Options Are Wrong:
12/16/36 are off by one or multiply the wrong number of times; there is no infinite loop because i grows and the condition fails at 7.


Common Pitfalls:
Misreading ++i as i++ or starting the count at 1 in the body.


Final Answer:
32

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion