+ 4

What is the error in this code?

I think there is some runtime error in the function fact() please check and suggest correction there is timeout https://code.sololearn.com/cWf0gZIk1J20/?ref=app

30th Dec 2017, 5:14 AM
Aditya
Aditya - avatar
5 ответов
+ 5
@Gordie, yes no need of else. int fact(int x) { if(x==0) return 1; for(int i=x; i>=1; i--) { x=x*i; } return x; } About x<o cases, yes we can do something like that but i think that @Aditya should handle it when getting inputs. Indeed the rest of the program only use positive values.
30th Dec 2017, 11:42 AM
Al Toe
+ 3
Just change x-- by i-- like this int fact(int x) { for(int i=x; i>=1; i--) { x=x*i; } return x; }
30th Dec 2017, 6:34 AM
Al Toe
+ 3
@Gordie, yeah you're right, i forgot that case. to handle it we can use "if else" before the loop. but for more elegance in the code it's better to use the recursive version suggested by @Sayantan
30th Dec 2017, 7:53 AM
Al Toe
+ 3
thank you guys now this code is working!
30th Dec 2017, 6:06 PM
Aditya
Aditya - avatar