Thread: Finding Factorial in C language.

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    12

    Finding Factorial in C language.

    Hi,

    I am working on a program that asks a user to enter a # between 1 to 50 and finds the factorial of that. It uses recursive function to find it.

    Here is what I got so far:

    Code:
    include <iostream>
    
    using namespace std;
    
    //function prototypes
    
    int getNum();
    int fact(int);
    void printResult(int, int);
    
    
    int main()
    {
    int num;
    int ans;
    
    num = getNum();
    ans = fact(num);
    printResult(num, ans);
    
    cout << endl << endl;
    }
    int getNum()
    {
    	int num;
    	cout << "\nEnter a number:";
    	cin >> num;
    	return num;
    }
    int fact(int num)
    {
    	
    	if (num == 0)
    		return 1;
    	else 
    		return num * fact(num - 1);
    	
    }
    void printResults(int num, int ans)
    {
    	cout <<"\nfactorial of" << num << "is : " << ans;
    	
    }
    Its not working, can some please help me solve this problem.

    Thanks

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Considering that you aren't writing C, you have just failed your class.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    If you want to hang on to this for your C++ class, then you should note that 50! does not fit in an int datatype. Either restrict the domain (a lot) further, or use a different data type.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-09-2010, 06:55 AM
  2. Finding out which language a program is written in.
    By billstarks in forum Tech Board
    Replies: 9
    Last Post: 06-07-2007, 06:13 PM
  3. What's the Difference Between a Programming Language and a Scripting Language?
    By Krak in forum A Brief History of Cprogramming.com
    Replies: 23
    Last Post: 07-15-2005, 04:46 PM
  4. how to add a factorial ()
    By correlcj in forum C++ Programming
    Replies: 14
    Last Post: 10-18-2002, 02:28 PM
  5. Computer Language VS Spoken Language
    By Isometric in forum A Brief History of Cprogramming.com
    Replies: 14
    Last Post: 02-04-2002, 03:47 PM