I have a recursive program. When the printf is used in the function, it outputs 123 and when used outside, it outputs 0123 .
#include <stdio.h>
fact(int);
int main()
{
int x=3;
fact(x);
printf("\n");
system("PAUSE");
}
int fact(int y)
{
if (y > 0)
{
fact(y-1);
printf("%d",y);
}
//printf("%d",y);
}
I am not using both the printf at the same time . What difference does the location of this printf statement create?
Since your if condition looks for the values greater than zero, it is working as expected.
When the printf outside that IF block is used, it gets executed even when y is 0, which is not the case for the printf inside the IF block.
fact(int) is called by following sequence,
fact(3)-->fact(2)--->fact(1)--->fact(0)
The last call is fact(0). According to the implementation of fact(int), when 0 is passed in, 0 is printed if printf() is used outsite. 0 is not printed if printf() is used inside.
In fact, all the values passed into fact(int) is printed when printf() is used outsite.
I'd say one reason you didn't see the answer yourself is because your code is sloppy. Here are some complaints:
Your functions have no explicit return statements which are
especially important for understanding recursive code.
system() requires stdlib, but stdlib.h isn't included.
system("PAUSE") is unportable and unnecessary. Actually your code
would not run on my system because of this. See:
http://www.gidnetwork.com/b-61.html
Your question looks like homework, so this one is the homework's fault and not yours: because n! grows so quickly, factorial functions using 'int' for the return type can only calculate n! for 1<=n<=12, which is useless.
Try this exercise: write a one-line factorial function using a single return and a conditional assignment.
Related
Please test this code and give me your answers :
#include <stdio.h>
int func() {
static int n = 0;
n++;
return n;
}
int main() {
/*int first = func();
int second = func();*/
printf(" first call : %d \n second call : %d ",func(),func());
return 0;
}
Logically it should print 1 and 2 but it is printing 2 and 1 .
If you Un-Comment the comments and print the variables "first" and "second" , the problem is solved!
What is happening?
thank you already!
The order in which a function call's arguments are evaluated is unspecified, i.e., the compiler is free to make the two func() calls in any order before passing the return values to printf. If you first assign the results to variables, obviously you get to decide in which order they are used.
The order in which the parameters to a function are passed is not defined in the standard, and is determined by the calling convention used by the compiler. I think in your case, cdecl calling convention (which many C compilers use for x86 architecture) is used in which arguments in a function get evaluated from right to left.
because while calling the function it takes right associative..
i.e, the last one in printf gets called first then the before one.. thats why it is printing 2 then 1.
try using two print statements like:
printf("First call: %d\n",func());
printf("second call: %d\n",func());
I wrote a C program to use recursive functions to find the factorial of a number and the code is given below:
//program to find factorial of a number using a recursive function
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int factorial(int a);
int main()
{
int num, fact;
printf("Enter a number: ");
scanf("%d", &num);
if(num<=0)
{
printf("The number cannot be zero/negative.");
exit(1);
}
fact=factorial(num);
printf("The factorial of the entered number is: %d", fact);
getch();
return 0;
}
int factorial(int a)
{
while(a>1)
return a*factorial(--a);
}
In the above code in 'while' loop if the input 'a'>1 then it should execute, but when i compile the program (using Dev C++ v.5.4.2) and give the input as 1, I get the factorial as 1. The program is the solution to the required problem, but i need to know what is actually happening in background...
Thank you in advance
int factorial(int a)
{
while(a>1)
return a*factorial(--a);
}
This function does not return anything if the condition in while loop is not true. Thus , invoking undefined behaviour (Maybe giving you correct output).
You should handle that case -
int factorial(int a)
{
if(a==1)return 1;
//while(a>1) // you use recursion then why using loop
return a*factorial(a-1);
}
In the case where a <= 1 your function does not have a return statement, even though it expects one. Which means you have a bug which will invoke undefined behavior: anything can happen, including: "seems to work ok", "weird output", the program crashes etc.
A half-decent compiler would warn you for this. For example GCC with warnings enabled:
warning: control reaches end of non-void function [-Wreturn-type]|
This is undefined behavior.
N1256 6.9.1 Function definitions
12 If the } that terminates a function is reached, and the value of the function call is used by
the caller, the behavior is undefined.
To know what is actually happening in this specific situration, have your compiler output assembly code and read it, or use debugger suce as OllyDbg.
Your compiler seems to allow omission of return value. What happens is that your "factorial" function will not execute the while() loop, and after the while loop there is no return statement, so the return value will be undefined.
int factorial(int a)
{
while (a>1) // a is 1 so this will be false, and the loop will not execute
return a*factorial(--a);
return 1; // this value will be returned
}
Also, I suggest you review this code (looks like a school exercise to me). Currently, although it may work correctly, the code differs from how an experienced programmer would implement it.
I am trying to understand the following program in which successive recursion function calls are present, but getting confused while tracing how the tack gets loaded.
void func(char*); // function prototype
int main(){
func("123");
return 0;
}
void func(char a[]){
if(a[1]=='\0')
return;
func(a+1);
func(a+1);
printf("%c",a[1]);
}
the output for this is 3 3 2
would appreciate if someone could advise on this one...
does this kind of multiple recursive calls beneficial in any way or find application in specific problem areas..?
Just put yourself in the position of the CPU and step through line-by-line (or use a debugger to help with that task).
The first call is to
func("123")
this call does not satisfy the termination condition a[1] == '\0', so it calls
func("23");
The call to func("23") in turn calls
func("3")
which DOES satisfy the return condition. So, that call returns to the previous caller, func("23").
func("23") proceeds to make another call to func("3") due to the lines
func(a+1);
func(a+1);
Continue this process of executing the program in your mind, and write down what would be in each call to printf. That will explain your output.
UPDATE
Note that the call to printf() happens after the recursive calls, so e.g. a call to
func("123")
would proceed like
Enter func("123")
Termination condition not met
Call func("23")
Call func("23") again
Printf("3") (which is a[1])
Return
Debugging with breakpoints is one way to understand recursion. Another way is to draw the tree of recursive calls.
From the figure, In every level after level0, the printf statement occurs after every two nodes owing to these two lines of code:
func(a+1);
func(a+1);
In general, this becomes a perfect binary tree for any input string of length greater than 0. The total number of nodes is given by this formula:
2^(k+1) - 1 // k is the depth; here k = 2
Total number of printf statements executed can be obtained by this formula:
2^k - 1 // For k=2, there will be 3 printf statements each printing 3,3,2 respectively
the posted code is a rather poorly designed instance of recursion.
The following code has the correct 'tail' form of recursion.
It could be made even better by passing the reversed string back to main and let main print it.
It reverses the order of the string passed to func() by main()
Please, when asking about a runtime problem, post code the compiles, including the necessary #includes for header files so we are not guessing about which headers to include
#include <stdio.h>
void func(char*); // function prototype
int main(){
func("123");
return 0;
}
void func(char a[])
{
if(a[1]=='\0') // check for end of recursive sequence
{
printf( "%c", a[0] ); // last tail action
return;
}
func(a+1); // step+next recursion
printf( "%c", a[0] ); // tail action
return;
}
The recursion can be simply understood as follows.
For example:
Func(int a){
while(a>1)
return a * func(a-1);
}
Suppose a = 5.
What happens is that it returns 5 * func(4).
Now func(4) returns 4 * func(3) and it goes on like this.
Check out this example for use of recursion in fibonacci series.
I understand declaring factorial before main. But how can main calculate the answer when the factorial formula comes after it?
#include <stdio.h>
long long factorial(int);
int main()
{
int n;
long long f;
printf("Enter a number and I will return you its factorial:\n");
scanf_s("%d", &n);
if (n < 0)
printf("No negative numbers allowed!\n"); //prevent negative numbers
else
{
f = factorial(n);
printf("The factorial of %d is %ld\n", n, f);
}
return 0;
}
long long factorial(int n)
{
if (n == 0)
return 1;
else
return (n * factorial(n - 1));
}
But how can main calculate the answer when the factorial formula comes after it?
First thing — main does not calculate the answer; it's your factorial function which does it for you. Also there are 3 steps which I feel you need to know about when writing programs:
You write the code in a file.
You compile the file and the compiler checks for syntactical mistakes, no code calculation is happening in this phase its just mere lexical analysis.
Then linking takes place later. If you receive a linker error, it means that your code compiles fine, but that some function or library that is needed cannot be found. This occurs in what we call the linking stage and will prevent an executable from being generated. Many compilers do both the compiling and this linking stage.
Then when you actually run your code — it's then when the code's control flow goes into the factorial function when the calculation happens, i.e. at runtime. Use a Debugger to see this.
The below image is taken from Compiling, Linking and Building C/C++ Applications
From Wiki:
In computer programming, a forward declaration is a declaration of an
identifier (denoting an entity such as a type, a variable, a constant,
or a function) for which the programmer has not yet given a complete
definition....
This is particularly useful for one-pass compilers and separate
compilation. Forward declaration is used in languages that require
declaration before use; it is necessary for mutual recursion in such
languages, as it is impossible to define such functions (or data
structures) without a forward reference in one definition: one of the
functions (respectively, data structures) must be defined first. It is
also useful to allow flexible code organization, for example if one
wishes to place the main body at the top, and called functions below
it.
So basically the main function does not at all need to know how factorial works.
But how can main calculate the answer when the factorial formula comes after it?
The order in which a C program executes is only partially determined by the order in which the text appears.
For instance, look at the printf function you are using. That doesn't appear in your program at all; it is in a library which is linked to your program.
The forward declaration makes it known (from that point in the translation unit) that there is expected to exist such and such a function having a certain name, arguments and return value.
The simple answer is that your C program is processed from beginning to end before it begins to execute. So by the time main is called, the factorial function has already been seen and processed by the C compiler.
An address is assigned to the compiled factorial function, and that address is "backpatched" into the compiled main function when the program is linked.
The reason forward declarations are needed at all is that C is an old-fashioned language originally designed to allow one-pass compilation. This means that the compiler "translates as it goes": functions earlier in a translation unit are compiled and emitted before later functions are seen. To correctly compile a call to a function which appears later (or, generally, appears elsewhere, like in another translation unit), some information must be announced about that function so that it is known at that point.
It works in this manner: let's take an example to find factorial of 3
Recursion :
As factorial of 0 is 1 and factorial of 1 is also 1, so you can write like
if(n <= 1)
return 1;
Since in main function when compiler sees this f = factorial(n); function, the compiler has no idea of what it means. it doesn't know where the function being defined, but it does know the argument the function is receiving is correct, because it's a user defined function that has its definition after main function.
Hence there should be some way to tell the compiler that I am using a function with name factorial which returns long long with a single int argument; therefore you define a prototype of the function before main().
Whenever you call the function factorial the compiler cross checks with the function prototype and ensures correct function call.
A function prototype is not required if you define the function before main.
Example case where function prototyping is not required :
/*function prototyping is not required*/
long long factorial(int n)
{
//body of factorial
}
int main()
{
...
f=factorial(n);
...
}
Here, the compiler knows the definition of factorial; it knows the return type, the argument type, and the function name as well, before it is called in main.
I have a pretty simple function in my program using the secant method to find a root of a function. It works fine with the printf() that's indicated below. But if I comment it out, the loop endlessly repeats. I have no idea why...
I've read about printf changing a variable, but I don't see anything on it changing the storage of the variable. Am I missing something? It's not a great solution to have it print, since the iterates are not important and the function is called millions of times.
double guess1=500.;
double y1=estimater(r,volume,guess1,adm,tm,rr[r]);
double guess2=adm/30.;
double y2=estimater(r,volume,guess2,adm,tm,rr[r]);
int i;
double guess3=0.;
double y3;
double tol =heightTOL;
int secmax=SECANTMAX;
for(i=1;i<=secmax;i++){
guess3=guess2-y2*(guess2-guess1)/(y2-y1);
if(guess3>adm/2.){
guess3=adm/2.;
}
if(guess3<=0.){
guess3=0.;
}
y3=estimater(r,volume,guess3,adm,tm,rr[r]);
y1=y2;
y2=y3;
guess1=guess2;
guess2=guess3;
if(fabs(guess2-guess1)<tol){
break;
}
if(i==secmax){
printf("\nRan out of iterations in height finder\n");
}
printf("%d %f",i,guess3); //THIS ONE HERE!!!!!!!!
}
return guess3;
printf is not changing your data at all. The only way the printf family of functions can have any effect on your data is if you use the %n format specifier (which writes into the variable whose address you pass) or if you're doing something which invokes undefined behavior, like passing the wrong format arguments. You're not doing either of those things here (your format strings are correct), so your bug lies elsewhere.
Check that all your array accesses are in bounds. Try running your code in Valgrind or other validators to try to find memory errors.