Thread: Factorial Using recursion not working

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    7

    Factorial Using recursion not working

    I wrote this factorial program, which i expected should have returned an answer, but i didn't. I know it has to be a small conceptual mistake, but i just couldn't get it. Please help!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int fact(int num);
    void main() {
        int number, factorial;
        printf("Enter Number :   ");
        scanf("%d", &number);
        factorial = fact(number);
        printf("Factorial : %d", factorial);
    }
    int fact(int num){
        int res ;
        if(num==0){
            return 1;
        }
        while(num!=0){
            res = num*fact(num-1);
        }
        return res;
    }
    The code compiles fine and even runs...but it just gets stuck at
    "factorial = fact(number);" in the main..

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Get rid of the while loop. It is an infinite loop here.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Code:
        while(num!=0){
            res = num*fact(num-1);
        }
    There, your infinite loop.

  4. #4
    C lover
    Join Date
    Oct 2007
    Location
    Virginia
    Posts
    266
    Code:
    #include <stdio.h>
    
    int factorial(int n){
    
        if(!n) return 1;
    
        return n * factorial( n - 1 );
    }
    
    int main(){
    
    
        printf("%d\n",factorial(6));
    
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Jul 2010
    Posts
    7
    Thanks guys!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help explaining test questions
    By Sentral in forum General Discussions
    Replies: 26
    Last Post: 11-09-2009, 11:10 PM
  2. Basic Factorial from 1-10
    By AaA in forum C Programming
    Replies: 20
    Last Post: 05-28-2005, 07:39 AM
  3. recursion project
    By Psycho in forum C++ Programming
    Replies: 4
    Last Post: 03-31-2002, 03:24 PM
  4. factorial output
    By maloy in forum C Programming
    Replies: 1
    Last Post: 03-13-2002, 03:28 PM
  5. Recursion help
    By james in forum C Programming
    Replies: 2
    Last Post: 09-04-2001, 01:29 AM