C Programming - Pointers - Discussion

Discussion Forum : Pointers - Point Out Correct Statements (Q.No. 8)
8.
In the following program add a statement in the function fact() such that the factorial gets stored in j.
#include<stdio.h>
void fact(int*);

int main()
{
    int i=5;
    fact(&i);
    printf("%d\n", i);
    return 0;
}
void fact(int *j)
{
    static int s=1;
    if(*j!=0)
    {
        s = s**j;
        *j = *j-1;
        fact(j);
        /* Add a statement here */
    }
}
j=s;
*j=s;
*j=&s;
&j=s;
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
28 comments Page 1 of 3.

SAHA said:   3 years ago
Wow. Nice explanation @Jas.

Mayur baviskar said:   3 years ago
Thanks @Kareena.

Kareena said:   4 years ago
Let's do with value of i=3.
1) *j=3 , s=1
s=s* *j; ----> s=1*3 ------> s=3
*j=*j - 1; ------> *j=2

2) *j=2 , s=3 (because s is static)
s=s* *j; ----> s=3*2 ------> s=6
*j=*j - 1; ------> *j=1

3) *j=1 , s=6 (because s is static)
s=s* *j; ----> s=6*1 ------> s=6
*j=*j - 1; ------> *j=0.

4) *j=0 , s=6 (because s is static)
while(*j!=0) ----> false.
It will have no effect.

5) Control back to step (3)
Value of s will remain same because it is static ---> s=6
*j =s; -----> *j=6

6) Control back to step (2)
Value of s will remain same because it is static ---> s=6
*j =s; -----> *j=6


7) Control back to step (1)
Value of s will remain same because it is static ---> s=6
*j =s; -----> *j=6

8) Control back to main
As it is call be refrence, i=*j ------> i=6.
(4)

Devansh said:   5 years ago
How come 120? Please anyone explain.

Akash said:   6 years ago
The answer should be j=s.

Neha said:   6 years ago
But j is having the address of i.. so *j means value at address of i and i will store the value. i think it should be j=s.

Abhishek said:   6 years ago
Explain it clearly for me.

Deepika said:   7 years ago
Please, anyone explain clearly.

Sujith said:   7 years ago
In unwinding phase, the last value of s becomes 5 then how it sends 120?

Please someone explain clearly.

RATHOD said:   7 years ago
Please anyone explain it properly.


Post your comments here:

Your comments will be displayed after verification.