What is wrong in this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is wrong in this code

#include <iostream> using namespace std; int fact(int n) { if ( n >= 0) { if ( n==1 || n==0 ) { return 1; } else { return n*fact(n-1); } } else { cout << "Sorry Wrong No "<< endl ; } } int main() { int a; cout << "Enter The No ="<< endl ; cin >> a; cout << "Factorial ="<< fact(a) ; return 0; }

4th Dec 2016, 6:43 PM
Arpit Joshi
Arpit Joshi - avatar
5 Answers
+ 3
When you give a negative number as input it gives some sort of additional number like 4620160.This code will solve that problem. you can use this code : #include <iostream> using namespace std; int fact(int n) { if ( n >= 0) { if ( n==1 || n==0 ) { return 1; } else { return n*fact(n-1); } } else { // cout << "Sorry Wrong No "<< endl ; return 0; } } int main() { int a,b; cout << "Enter The No ="<< endl ; cin >> a; b=fact(a); if(b!=0) cout << "Factorial ="<< b ; else cout<<"sorry wrong no"; return 0; }
7th Dec 2016, 5:37 AM
Rishabh Agrawal
Rishabh Agrawal - avatar
+ 1
I just ran it and it worked fine. What compiler are you using?
4th Dec 2016, 8:48 PM
Ben
Ben - avatar
0
what is the error you get while compiling ?
4th Dec 2016, 6:49 PM
Towkir Ahmed
Towkir Ahmed - avatar
0
This code is giving a factorial for negative no also🤔
4th Dec 2016, 6:52 PM
Arpit Joshi
Arpit Joshi - avatar
0
M using this app
4th Dec 2016, 8:48 PM
Arpit Joshi
Arpit Joshi - avatar