Consider the function in C code: void Cal(int a, int b) { if (b != 1) { if (a…
2024
Consider the function in C code:
void Cal(int a, int b)
{
if (b != 1)
{
if (a != 1)
{
printf("*");
Cal(a / 2, b);
}
else
{
b = b - 1;
Cal(10, b);
}
}
}
How many times * is going to be printed, if the function is called with Cal(10, 10); ?
- A.
25
- B.
23
- C.
24
- D.
27
Attempted by 169 students.
Show answer & explanation
Correct answer: D
Assumption: the else is paired with the inner if (a != 1). That means when a becomes 1, the code decrements b and resets a to 10, creating nested behavior.
Computation:
Each time a starts at 10 and is integer-divided by 2 until it becomes 1, stars are printed for the steps: 10 → 5 → 2 → 1. That prints 3 stars per inner cycle.
b starts at 10 and the outer process continues while b != 1. Each time a reaches 1 we decrement b and reset a to 10. So b takes values 10, 9, ..., 2 — a total of 9 cycles.
Total stars printed = 3 stars per inner cycle × 9 cycles = 27.
Final answer: 27
Note: If the else were attached to the outer if (b != 1) instead, the function would only print 3 stars in total (for a = 10 → 5 → 2 → 1) because b would never change from 10. The intended interpretation yields 27.
A video solution is available for this question — log in and enroll to watch it.