0
Whenever i write int(num > 1)the output is"factorial of 5 is 1"and if i write int(num <1)the output comes "factorial of 120"why?
8 Respostas
+ 7
Muhtasinul sometimes a simple approach is more than helpful 😉
https://code.sololearn.com/cnD2ltiUwoNM/?ref=app
+ 3
Mind referring to the code? :)
+ 2
Paste your code to get help cause we can understand your problem!!
+ 1
Muhtasinul Are you uncertain about how the if/else statement works? It is important to understand before trying to learn recursion.
You might consider reviewing the lesson on if/else here:
https://www.sololearn.com/learn/C/2923/
By changing the condition from (num<1) to (num>1) you force the function to immediately return (1). This is because num=5, so (num >1) evaluates to true, and when the conditonal is true it executes return(1);. It never executes the 'else' clause that would do the recursion.
This is an aging question, but I see there is no accepted answer yet. Be sure to mark which answer is your accepted answer, or else clarify what more you need.
0
#include <stdio.h>
//function declaration
int factorial(int num);
int main() {
int x = 5;
printf("The factorial of %d is %d\n", x, factorial(x));
return 0;
}
//function definition
int factorial(int num) {
if (num > 1) /* base case */
return (1);
else
return (num * factorial(num - 1));
}
0
#include <stdio.h>
//function declaration
int factorial(int num);
int main() {
int x = 5;
printf("The factorial of %d is %d\n", x, factorial(x));
return 0;
}
//function definition
int factorial(int num) {
if (num < 1) /* base case */
return (1);
else
return (num * factorial(num - 1));
}
0
Plz mark that if(num <1) shows output factorial of 5 is 120 and if(num >1)shows output factorial of 5 is 1,why?