+ 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
4 Answers
+ 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.
+ 3
Just change x-- by i-- like this
int fact(int x) {
for(int i=x; i>=1; i--) {
x=x*i;
}
return x;
}
+ 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
+ 3
thank you guys now this code is working!