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? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

21st Jul 2020, 11:59 AM
Muhtasinul
Muhtasinul - avatar
7 Answers
+ 7
Muhtasinul sometimes a simple approach is more than helpful 😉 https://code.sololearn.com/cnD2ltiUwoNM/?ref=app
3rd Sep 2020, 12:05 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 3
Mind referring to the code? :)
21st Jul 2020, 12:00 PM
Ćheyat
Ćheyat - avatar
+ 2
Paste your code to get help cause we can understand your problem!!
21st Jul 2020, 12:01 PM
Rawley
Rawley - avatar
+ 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.
15th Sep 2020, 3:02 PM
Brian
Brian - avatar
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)); }
21st Jul 2020, 1:08 PM
Muhtasinul
Muhtasinul - avatar
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)); }
21st Jul 2020, 1:10 PM
Muhtasinul
Muhtasinul - avatar
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?
21st Jul 2020, 1:11 PM
Muhtasinul
Muhtasinul - avatar