C Programming - Functions - Discussion

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

int main()
{
    int k=35;
    k = func1(k=func1(k=func1(k)));
    printf("k=%d\n", k);
    return 0;
}
int func1(int k)
{
    k++;
    return k;
}
k=35
k=36
k=37
k=38
Answer: Option
Explanation:

Step 1: int k=35; The variable k is declared as an integer type and initialized to 35.

Step 2: k = func1(k=func1(k=func1(k))); The func1(k) increement the value of k by 1 and return it. Here the func1(k) is called 3 times. Hence it increements value of k = 35 to 38. The result is stored in the variable k = 38.

Step 3: printf("k=%d\n", k); It prints the value of variable k "38".

Discussion:
16 comments Page 2 of 2.

Ranjeet said:   8 years ago
The answer will be 38.

if return k++;
will be given then the value will be
35

Ranjeet kr said:   8 years ago
The right answer will be 38.

If there will be statement like this,

return k++ then the value will be 35
and 35 will be also in other case if
we declare as the extra variable as follows
int i =k++;
return i;

Shubham said:   5 years ago
Nice explanation and I agree @Ranjeet Kr.

Rachana said:   5 years ago
That's post Decrement so it should be 35.

Varun ranjan said:   4 years ago
# include <stdio.h>


int post(int i)
{
int m=i++;
return m;//////return then increment
}

int post3(int k)
{
k++;
return k;//////increment then return
}

int post2(int j)
{
return j++;/////return then increment
}


int main()
{
int i =10;
printf("%d\n", post(i));


int j=20;
printf("%d\n", post2(j));


int k=23;
printf("%d",post3(k));
return 0;
}

Pratik said:   3 years ago
I agree, thanks @Priya.


Post your comments here:

Your comments will be displayed after verification.