what is the working rule of this program, Explanation? - c

i am little confuse in this program i want if anyone could explain to me the functionality of this code and the output, i am getting the output of this program as such
1
1
2
2
3
3
All i want to know the working rule of that two functions how they calculating the values?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int M(const int n);
int F(const int n)
{
return(n==0)?1:n-M(F(n-1));
}
int M(const int n)
{
return (n==0)?0:n-F(M(n-1));
}
int main()
{
int i;
for(i=0;i<6;i++)
{
printf("%2d\n",F(i));
}
printf("\n");
return 0;
}

Consider on for
for(i=0;i<6;i++)
{
printf("%2d\n",F(i));
}
Short answer:
F(0) => 1;
F(1)=> 1 - M(F(0))
when F(0):1 then F(1) = 1 - M(1)
go to calculate M(1), but we start from 0, M(0)= 0;
M(1) = 1- F(M(0)) = 1- F(0) = 1-1=0;
last we have M(1) = 0; and as F(1) = 1-M(1) = 1-0=1
last we have: F(1)=1
More complete:
Let see F() way of working.
the last command in F(),
return(n==0)?1:n-M(F(n-1));
expanded to
if (n==0){
return 1;
}else{
return n-M(F(n-1));
}
In first for iteration i:0, we want F(0) as n is zero, (n:0), the if (n==0) is true , return 1; is executed and value ofF(0) have to be 1.
for second iteration we want F(1), for that if (n==0) is false and else block is execute.
as now the n:1, F(1) = 1 - M (F(0)).
In previous iteration we have F(0)=1, OK now we can rewire or equation: F(1) = 1 - M(1), it obvious that if we have value of M(1) simply , put it on to the last formula , F(1) have been solved.
for this we must expand M() function.
Similarly we can write for M().
if (n==0){
return 0;
}else{
return n-F(M(n-1));
}
M(0) = 0;
M(1)= 1- F(M(0))= 1- F(0) = 1 - 1=0;
now we have M(1) = 0; by putting it on the F(1) = 1 - M(1)
we achieve to F(1) = 1.
Now the first two pair of 1 in output of your code is calculated by hand.
for others, do this way over and over.

As suggested in the comments try to trace the code by hand, I will go through the first two iterations with you so you get the idea
When your program starts it calls your main function, and starts executing the for loop as follows:
i=0 => calls F(n=0) => is n==0 true? Yes => return 1 => print 1
i=1 => calls F(n=1) => is n==0 true? No => then 1-M(F(0)) => F(0) calculated from the previous iteration to return a value of 1 => call M(n=1) => is n==0 true? No => then 1-F(M(0)) => M(0) returns 0 since n==0 is true => then 1-F(M(0)) is equal to 1-F(0) => we calculated F(0) to return 1 => so 1-F(0) return 0 from M => take the return back to 1-M(F(0)) => 1-0 = 1 => print 1
Do not be frustrated because what you are asking would be actually much easier to understand with some patient. I extremely recommend that you hold down a pen and paper and start tracing yourself.
Go iteration by iteration as I did.
Call each function according to the correct flow of the if conditions.
When you call a function, mark where you have left in the code to jump to said function, such that once it returns a value, you know exactly where to place the returned value.
Peace of paper, patience, and trace.

Related

How does the for loop run in such a case?

#include <stdio.h>
int f1(){
static int val=11;
return --val;
}
int main()
{
for( f1(); f1(); f1()){
printf("%d",f1());
}
}
The output of the program is :
8 5 2
Could someone explain me what does for(f1();f1();f1()) do?
#include <stdio.h>
int foo(void) {
static int val = 11;
return --val;
}
int main(void) {
int (*f1)(void) = foo; //4 function pointers to the same function
int (*f2)(void) = foo;
int (*f3)(void) = foo;
int (*f4)(void) = foo;
for (f1(); f2(); f3()) {
printf("%d", f4());
}
}
The execution goes like this
val = 11
f1() 10
f2() 9 "true"
f4() print 8
f3() 7
f2() 6 "true"
f4() print 5
f3() 4
f2() 3 "true"
f4() print 2
f3() 1
f2() 0 "false"
For easier understanding I'll talk about functions as such:
for (A(); B(); C()) {
printf("%d", D());
}
So understand that all A B C and D are calls to f1() but I want to be able to differentiate them.
1st thing to understand is how are the "parameters" of for working.
1st one is the init part, it will be executed once only, before the evaluation of the first condition.
2nd one is the condition part, it will be executed before every loop, to check if it needs to keep looping or stop.
3rd one is the conclusion part, it will be executed after every loop, before the next evaluation of the condition.
We can then understand that your program will execute in this order:
call A() to initialize the for loop => val = 10;
call B() to check condition => val = 9
call D() in your printf => val = 8 gets printed
call C() to end an iteration => val = 7
call B() to check condition => val = 6
call D() in your printf => val = 5 gets printed
call C() to end an iteration => val = 4
call B() to check condition => val = 3
call D() in your printf => val = 2 gets printed
call C() to end an iteration => val = 1
call B() to check condition => val = 0 condition ends
The C for loop contains 3 items:
the initialisation
the condition
the incrementation
A for loop run until the condition is equal to either 0 or null.
You enter the loop, it call f1() a first time in the initialisation so val equal 10
At each iteration, it will call f1() three time, to check the condition, to do the increment part and in the printf call. Thus at each iteration we have val = val - 3
Once val == 0 you exit the loop.
Note that it only work because val is static thus not being reinitialised at each call of f1()

Recursive function in C (to print a piramid of #)

I´m following the famous course cs50.
During a class, the teacher showed a program that printed out a pyramid of a height given as an input from the user:
#include <cs50.h>
#include <stdio.h>
void pyramid(int n);
int main (void)
{
int height = get_int("height:");
pyramid(height);
return 0;
}
void pyramid(int n)
{
if (n==0)
{
return;
}
pyramid(n-1);
for (int i=0; i<n;i++)
{
printf("#");
}
printf("\n");
}
Can please someone explain me, what the recursive function pyramid does?
I debug it and I see that given the input is checking if it is equalto 0, then it calls itself until n==0 and returns. After that the debugger goes to the loop for and does it n time.
Following a liner path, it is not supposed to go to the for loop.
Why it does it?
Thank you very much for your help!
After some value of height is set, then a function piramid is called. If the value of height is 0, then the function finishes. Otherwise it calls itself with decreased argument height, which allows you to print each level of the pyramide. As you can see in the body of void piramid(int n), it calls itself first, then prints n "blocks".
Let's say we are working with height = n and try to analyze what happens (each dot is another step):
piramid(n) calls:
piramid(n-1) calls:
piramid(n-2) calls:
...
piramid(1) calls:
piramid(0) - that returns nothing, it is the last recursive call of piramid, so we start going back: in our case it means we print hashes in the order from top to bottom:
# is printed, as piramid(1) is on top of the stack and after we print it, then we pop it, so piramid(2) becomes the first element on top
## are printed, piramid(2) is on top of the stack, we pop it and continue working with other calls the same way,
...
(n-1) # are printed, we pop it from the stack,
n # are printed, our stack is now empty.
To make it understandable, let's take an example with a small number :
#include <stdio.h>
void piramid (int n);
int
main (void)
{
piramid (2);
}
void
piramid (int n)
{
if (n == 0)
{
return;
}
piramid (n - 1);
for (int i = 0; i < n; i++)
{
printf ("#");
}
printf ("\n");
}
What it does:
main calls piramid(2)
piramid(2) calls piramid(1) however piramid(2) didn't finish as you stated
piramid(1) calls piramid(0)
piramid(0) does nothing as it returns immediately
piramid(1) finishes and prints #
piramid(2) finishes and prints ##
If n was bigger it would follow this but with more steps
Hope it could help and sorry if my answer isn't great as it's my first try answering on stackoverflow (if you have suggestions of how I should answer don't hesitate to tell me)

How to approach this kind of recursion program

The answer of simple recursion problem is easy to predict but when it involves multiple calls at a time then it gets difficult (here e(--n) is called two times
in single block of scope).
My problem is how to solve this kind of programs by creating TREE kind of structure
void e(int);
int main(void)
{
int a = 3;
e(a);
putchar('\n');
return 0;
}
void e(int n)
{
if (n > 0)
{
e(--n);
printf("%d ", n);
e(--n);
}
}
If you do it on a piece of paper with a pencil you should get this:
call => e(3);
call => e(2);
call => e(1);
call => e(0);
initial printf: 0
call => e(-1);
initial printf: 1
call => e(0);
initial printf: 2
call => e(1);
call => e(0);
initial printf: 0
call => e(-1);

C program for solving equation using bisection method

this program is for solving equation using bisection method gives error "function show return a value".
In this method we are given a function f(x) and we approximate 2 roots a and b
for the function such that f(a).f(b)<0.
Then we find another point
c=(a+b)/2
if f(c)==0
then root=c;
else
if f(a).f(c)<0
b=c;
if f(b).f(c)<0
a=c;
and we repeat these steps for the given number of iterations
#include<stdio.h>
#include<math.h>
#define e 0.000001/*e is the prescribed accuracy*/
main()
{
double g1,g2,g,v,v1,v2,prev;
int found=0,converged=0,i=0;
double f(double);
printf("We apply Bisection method to find a real root of the non-linear equation f(x) = 0, where f(x) = x^(2.7182818)-3cosx+1n");
while(found==0)/*This loop will continue until a range is found in between which a real root lies*/
{
printf("nEnter the first guess : ");
scanf("%lf",&g1);
v1=f(g1);
printf("nEnter the second guess : ");
scanf("%lf",&g2);
v2=f(g2);
if(v1*v2>0)
{
found=0;
g1++;
printf("nRoot does not lie in [%lf,%lf].n",g1-1,g2);
printf("nn..Enter two new guesses..nn");/*Previous two guesses are inappropriate*/
}
else
found=1;
}
printf("nThere is a real root which lies in [%lf,%lf].n",g1,g2);
while(converged==0)/*This loop will continue until a real root is found*/
{
printf("nnIteration = %dnn",i);
printf("a[%d](-ve)tb[%d](+ve)tbbx[%d]=(a[%d]+b[%d])/2tf(x[%d])n",i,i,i+1,i,i,i+1);
printf("%lft",g1);
printf("%lft",g2);
g=(g1+g2)/2;
v=f(g);
printf("%lft",g);
printf("t%lf",v);
if(v<0)
g1=g;
else
g2=g;
if(fabs(prev-v)<e)
converged=1;
else
prev=v;
i=i+1;
}
printf("nnThe approximate value of the root is : %lfn",g);
}
/*This function returns values of f(x)*/
double f(double x)
{
return pow(2.7182818,x)-3*cos(x)+1;
}
When tested with initial values of 1, and 2 and an iteration of 20, the result comes out to 1.154172. which is a root of the system.
When tested with inital values of 1, 1, and iteration of 20, the result comes out to 1.0000, which is wrong.
You should check that the initial conditions for the roots are met, i.e. f(a) * f(b) < 0.
f(1) = -1, f(1)* f(1) = +1, therefore the initial conditions are not satisfied in the second case.

Simple Recursion output calling recursion twice

This is how I tried it. The main part uses fun(9). So 9 does not equal or less than one. And it calls fun(9/3) two times and prints n which is 9. Where am I wrong here?
#include <stdio.h>
void fun(int n){
if(n<=1) printf("*");
else{
fun(n/3);
fun(n/3);
printf("%d",n);
}
}
int main(void){
fun(9);
return 0;
}
When called as fun(9), the code shown does print **3**39.
The first call has n == 9.
Consequently, if calls fun(3), then fun(3) again, and then prints 9.
The first of the two calls fun(3) calls fun(1), which prints a *, then calls fun(1) again and prints another *, and then prints 3.
The second of the two calls does the same.
Your output should be
* * 3 * * 3 9
If you can't see how it works, then do it by hand and fill in the values instead of the variable name:
Pass 1:
void fun(9){ // first pass n=9
if(9<=1) printf("*"); // nope, that's not true
else{
fun(9/3); // call the function again with n = 9/3 = 3
Pass 2:
void fun(3){ // second pass n=3
if(3<=1) printf("*"); // nope, that's not true
else{
fun(3/3); // call the function again with n = 3/3 = 1
Pass 3:
void fun(1){ // third pass n=1
if(1<=1) printf("*"); // yes! so print first *
else{ // this function is only an if and an else, we hit the if
// so it just drops out now
So pass #3 and we hit the lowest level of the recursive call, now Pass 2 will continue execution where it left off:
Pass 2b:
void fun(3){ // second pass n=3 (did this already)
if(3<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(3/3); // call the function with n = 1 (did this already)
fun(3/3); // next recursive call, again with n = 1
Now this will repeat the "pass #3" code, again printing a second *, then it will return and continue execution where it left off:
Pass 2c:
void fun(3){ // second pass n=3 (did this already)
if(3<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(3/3); // call the function with n = 1 (did this already)
fun(3/3); // call again with n = 1 (did this already)
printf("%d", 3); // print 3
At this point the output is: **3 Pass #2 is now complete so we go all the way back up and resume Pass #1 where it left off:
Pass 1b:
void fun(9){ // first pass n=9 (did this already)
if(9<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(9/3); // call the function again with n = 3 (did this already)
fun(9/3); // now call the function again with n = 9/3 = 3
From here you can see that we're going to repeat the Pass 2 logic producing another **3 then we'll return to Pass1 a final time to print the 9
A final output of: **3**39

Resources