ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
void printPattern(int n) {
    if (n == 0) return;
    printPattern(n - 1);
    for (int i = 0; i < n; i++) printf("*");
    printf(" ");
}
int main(void) {
    printPattern(3);
}
  1. A. *** ** *
  2. B. * * *
  3. C. Undefined behaviour
  4. D. * ** ***

Correct answer: D. * ** ***

The recursive call happens BEFORE the printing code, so the deepest call (n=0, which returns immediately) effectively runs first in terms of printed output; printPattern(1) then prints one '*', printPattern(2) prints two '**', and printPattern(3) finally prints three '***' last, in that increasing order: * ** *** .

More C Programming questions

Exams that ask this topic