Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c - Explanation of a program using functions

#include <stdio.h>

float a(int n);

main()
{
    int N;
    float z;
    puts("Dose to n (>=2)");
    scanf("%d",&N);
    z=a(N);
    printf("Gia n=%d h anadromikh sxesh dinei %f
",N,z);
}


float a(int n)
{  
    if(n==2)
        return (7);
    else if(n==3) 
        return ((8*49-1)/1);
    else 
        return ((8*a(n-1)*a(n-1)-1)/a(n-2));


}

guys can you please explain me how this program works? i mean, if i put for example n=8 , how will it find a7,a6 etc so it get the a8 ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically,

In CC++ Programming the function call work on Stack Segment in Memory.See Here

and in your program you are calling function recursively.

return ((8*a(n-1)*a(n-1)-1)/a(n-2)); at this stage for input n = 8

The function all will be

for a(8)->(8*a(7)*a(7)-1)/a(6)))

for a(7)->(8*a(6)*a(6)-1)/a(5)))

for a(6)->(8*a(5)*a(5)-1)/a(4)))

for a(5)->(8*a(4)*a(4)-1)/a(3)))

for a(4)->(8*a(3)*a(3)-1)/a(2)))

for a(3) program will return (8*49-1)/1

for a(2) program will return (7)

These all function will get its own stack segment in stack memory.

And the stack segment as it works on LIFO.

the stack segment will be from Last a(8)->a(7)->a(6)->a(5)->a(4)->a(3)->a(2) and it depends on the compiler`s function calling methodology so stack segment function calling may vary. hope this will help you to understand.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...