C Programming - Functions - Discussion

Discussion Forum : Functions - Find Output of Program (Q.No. 13)
13.
What will be the output of the program?
#include<stdio.h>
int i;
int fun1(int);
int fun2(int);

int main()
{
    extern int j;
    int i=3;
    fun1(i);
    printf("%d,", i);
    fun2(i);
    printf("%d", i);
    return 0;
}
int fun1(int j)
{
    printf("%d,", ++j);
    return 0;
}
int fun2(int i)
{
    printf("%d,", ++i);
    return 0;
}
int j=1;
3, 4, 4, 3
4, 3, 4, 3
3, 3, 4, 4
3, 4, 3, 4
Answer: Option
Explanation:

Step 1: int i; The variable i is declared as an global and integer type.

Step 2: int fun1(int); This prototype tells the compiler that the fun1() accepts the one integer parameter and returns the integer value.

Step 3: int fun2(int); This prototype tells the compiler that the fun2() accepts the one integer parameter and returns the integer value.

Step 4: extern int j; Inside the main function, the extern variable j is declared and defined in another source file.

Step 5: int i=3; The local variable i is defines as an integer type and initialized to 3.

Step 6: fun1(i); The fun1(i) increements the given value of variable i prints it. Here fun1(i) becomes fun1(3) hence it prints '4' then the control is given back to the main function.

Step 7: printf("%d,", i); It prints the value of local variable i. So, it prints '3'.

Step 8: fun2(i); The fun2(i) increements the given value of variable i prints it. Here fun2(i) becomes fun2(3) hence it prints '4' then the control is given back to the main function.

Step 9: printf("%d,", i); It prints the value of local variable i. So, it prints '3'.

Hence the output is "4 3 4 3".

Discussion:
18 comments Page 2 of 2.

Sherine said:   10 years ago
What about the variable j?

Srishti said:   1 decade ago
What is the use of j=1 here?

Anu said:   1 decade ago
How can the global variable i once incremented to 4 in fun2() after returning to main() prints 3?

Robin said:   1 decade ago
What about j=1?

Sayali said:   1 decade ago
Scope local variable is limited for corresponding function.

Preeti said:   1 decade ago
++i means first increment the value then print i.

i++ means print the value then increment the i.

Therefore in step 6 and step 8 they have incremented the value then printed the i.

Ashish said:   1 decade ago
Local variable get preference then global variable so when it return to main it prints 3.

Hari said:   1 decade ago
I am not understanding from step6 to step9. Please do explain it.


Post your comments here:

Your comments will be displayed after verification.