Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program

#include <stdio.h>
void fun(int);

int main(int argc)
{
    printf("%d ", argc);
    fun(argc);
    return 0;
}
void fun(int i)
{
    if(i!=4)
        main(++i);
}

 

  • A.1 2 3
  • B.1 2 3 4
  • C.2 3 4
  • D.1

Answer: B

Correct answer: 1 2 3 4

main is declared with only argc, which is 1 when the program is run without arguments, so 1 is printed first.

fun(1) then finds i != 4 and calls main(2), which prints 2 and calls fun(2), and so on. When fun(4) is reached the test fails and the recursion stops, having printed 1 2 3 4. Calling main recursively is legal in C, though not in C++, and is a curiosity rather than a technique.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.