C++ default arguments and integer truncation: what is printed by this program?\n\n#include<iostream.h>\nint main()\n{\n float Amount;\n float Calculate(float P = 5.0, int N = 2, float R = 2.0);\n Amount = Calculate();\n cout << Amount << endl;\n return 0;\n}\n\nfloat Calculate(float P, int N, float R)\n{\n int Year = 1;\n float Sum = 1;\n Sum = Sum * (1 + P * ++N * R);\n Year = (int)(Year + Sum);\n return Year;\n}

Difficulty: Easy

Correct Answer: 32

Explanation:


Introduction / Context:
This question tests how default arguments are applied in C++, how pre-increment affects an argument inside a function, and how casting/truncation impacts the returned value. The function computes a simple expression and then casts to int before returning as float.


Given Data / Assumptions:

  • Call is Calculate(), so defaults are used: P = 5.0, N = 2, R = 2.0.
  • Inside the function, ++N increments N to 3.
  • Sum is updated and then added to Year, which is cast to int.


Concept / Approach:
Compute the expression Sum = 1 * (1 + P * ++N * R). With the defaults, P * ++N * R = 5.0 * 3 * 2.0 = 30. Then 1 + 30 = 31. This value is added to Year (1), producing 32. Casting to int is harmless here because the value is integral; it would truncate fractional parts in other cases.


Step-by-Step Solution:
1) Defaults applied: P=5.0, N=2, R=2.0. 2) Pre-increment: ++N → 3. 3) Sum = 1 + 5.0 * 3 * 2.0 = 31. 4) Year = (int)(1 + 31) = 32. 5) Function returns 32.0; cout prints 32.


Verification / Alternative check:
If R were 1.5, the pre-increment would still occur first, and truncation would matter if the total were non-integer.


Why Other Options Are Wrong:
21/22/31 come from skipping ++N or misplacing parentheses; “None of these” is unnecessary since 32 is directly computed.


Common Pitfalls:
Forgetting the pre-increment on N and misunderstanding that the cast happens after the addition.


Final Answer:
32

More Questions from Functions

Discussion & Comments

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