Home » Data Structure

Find the factorial of any number with the use of tail recursion



In this article we are going to learn how to use tail recursion and also implement it to find the factorial of the number?
Submitted by Manu Jemini, on January 13, 2018

What is factorial?

Factorial can be understood as the product of all the integers from 1 to n, where n is the number of which we have to find the factorial of.

Example:

    Input number: 5
    Output:
    Factorial is: 120
    Explanation: 1 * 2 * 3 *4 * 5 = 120  

You may have noticed that the operation always remain same or we can say that its business logic never changes. Taking this into the account we can think about which approach to choose. You can do this with looping but we have chosen Recursion. Now what recursion refers to is like an approach to the flow of data and control?

When a function calls itself, again and again, it said to be a recursion.

factorial of a number in C

http://1.bp.blogspot.com/-ezSpp0vDQSo/VerVHxsgY8I/AAAAAAAADtg/VAKkf_HYJdk/s1600/factorial%2Bin%2BJava.gif

C program for factorial using recursion

#include<stdio.h>

//function that will return factorial
//this function will be executed recursively 
int factorial( int n, int fact )
{
	if ( n==1 )
		return fact;
	else
		factorial( n-1, n*fact );
}

//main function to test above function
int main( ){
	int n,value;
	
	//input an integer number 
	printf( "Enter the number : " );
	scanf( "%d", &n );
	
	if ( n < 0 )
		printf( "No factorial of negative number\n" );
	else if ( n==0 )
			printf( "Factorial of  zero is 1\n" );
	else
	{
		value = factorial( n,1 ); /* Function for factorial of number */
		printf( "Factorial of %d = %d\n",n,value );
	}

	return 0;
}

Output

output - factorial of a number in C





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.