Is this program correct?
Also, what comments should I put in the program?
Write a program that requests a factorial position from the user and calculates it using recursion
#include<stdio.h>
int factorial (int n);
int main()
{
int n;
printf ("Enter a positive integer");
scanf ("%d",&n);
printf ("factorial of %d=%ld", n,factorial(n));
return 0;
}
int factorial(int n)
{
if (n!=1)
return n*factorial(n-1);
}
PLEASE USE CODE TAGS (the <> formatting button) when posting code. http://v2.cplusplus.com/articles/jEywvCM9/
It makes it easier to read your code and it also makes it easier to respond to your post.
Hint: You can edit your previous post, highlight your code and press the <> formatting button.
printf ("factorial of %d=%ld", n,factorial(n));
You're telling printf() that factorial() returns a long, but it actually returns an int. Either change %ld to %d or change factorial() to return a long.
1 2
if (n!=1)
return n*factorial(n-1);
What if n==1? factorial() won't return anything in that case, which is undefined behavior.
This is a very common mistake. When writing recursive code, we're always thinking about the recursion and not the base case. For that reason, I always write recursive functions with this pattern:
1 2 3 4 5 6 7 8
func(parms)
{
if (this is the base case) {
return whatever;
} else {
do the recursion
}
}
The pattern makes the code easy to read and easy to write.
What do you mean by a "factorial position"? Is it just the user inputting a number, say 6, and getting back 6! ?
Or is it a user typing in 6 and 3 and the programming spitting out 6 * 5 * 4 * 3 * 2 * 1 (third position)
Or am I interpreting your question incorrectly? Because otherwise, what you already have in your factorial() function is good, and as @dhayden and @AbstractionAnon mentioned, you just need to add in a base case.
Btw adding the base case at the if statement is known as tail-end recursion, and it's safer than having it the other way around.
I have put a loop in it and I don't know where it should go.
You haven't said what the loop is supposed to do, so how do you expect us to tell you where to put it?
Just a wild ass guess, but if you meant to generate factorials from 1 to n, then wrap line 8 in a for loop.
You have been asked to use code tags. PLEASE DO SO. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
If you're not going to make the slightest bit of effort to make your posts readable, why should we spend the slightest bit of effort helping you?
I will not respond further until you apply code tags.