Thread: Recursion help

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    6

    Recursion help

    I need to write a program, something like this: Write a program which prompts the user for a number between 1 and 50 and which passes that number to a function which calculates the factorial of the number. The function must return the answer and main() must print it. Use recursion.What can be wrong.PLEASE

    #include<stdio.h>
    int factorial (int a,int b);
    void main (void)
    {
    int fact;
    printf("Enter a number between 1 and 50: ");
    scanf("%d",&x);
    fact=factorial (x,50);
    printf("The factorial is %d",fact);

    }
    int factorial (int a,int b)
    {
    return (factorial 50/(b-a));

    getchar();
    }

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    you are not working out the factorial properly....

    Code:
    unsigned long factorial(unsigned long number)
    {
    if (number<=1) 
    return 1;
    else
    return number*factorial(number-1);
    }
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Anti-Terrorist
    Join Date
    Aug 2001
    Location
    mming, Game DevelopmentCSR >&<>&2Minimization of boolean functions, PROM,PLA design >&0>&WA, USA guitar, dogsCommercial Aviation >&>>&USAProgramming
    Posts
    742
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    unsigned long factorial(int num)
    {
    	unsigned long ans;
    
    	if (num> 0) 
    		ans = num * factorial(num-1);
    	else
    		ans = 1;
    	return ans;
    }
    
    int main()
    {
    	int num;
    	printf("Enter number between 1 and 15: ");
    	while( scanf("%d",&num)!= 1 || num < 0 || num > 15)
    	{
    		while(getchar() != '\n') continue;
    		printf("Try again: ");
    	}
    	printf("Factorial = %ld\n", factorial(num));
    	return 0;
    }
    You can't go any higher than 15 unless you use compiler specific data types such as __int64 on a Microsoft OS
    Last edited by Witch_King; 09-04-2001 at 01:32 AM.
    I compile code with:
    Visual Studio.NET beta2

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  2. convert Recursion to linear can it be done
    By umen242 in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2008, 02:58 AM
  3. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  4. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 10:56 AM
  5. To Recur(sion) or to Iterate?That is the question
    By jasrajva in forum C Programming
    Replies: 4
    Last Post: 11-07-2001, 09:24 AM