Write a Program in C to Calculate the Factorial Value of an Integer.

468x60

Program in C to Calculate the Factorial Value of an Integer
Here is a program in C to calculate the factorial value of an integer.

The factorial of a number is the product of all the integers between 1 and that number.  For example factorial of 5 is 5*4*3*2*1. This can also be expressed as 5!=5*4!, where '!' stands for factorial.

Hence factorial of a number can also be programmed using recursion. Here I have given two methods for calculating factorial of a number, using non-recursive function and using recursive function.




Non-recursive function for calculating the factorial value of an integer

 

Steps:

  1. Declare prototype for the function named factorial() used to calculate factorial value.
  2. Declare two integers a and fact.
  3. Prompt the message to enter any number to calculate the factorial.
  4. Allow the user to enter number using scanf().
  5. Use function factorial() to calculate the factorial value and return that.
  6. Print the returned value to the screen using printf() command. 

 

code:


#include <stdio.h>


int factorial(int);


int main()
{
int a, fact;

printf("Enter any number");
scanf("%d",&a);

fact=factorial(a);
printf("Factorial value-%d\n", fact);
return 0;
}

int factorial(int x)
{
int f=1,i;

for(i=x;i>=1; i--)
f=f*i;

return(f);

}



Recursive function for calculating the factorial value of an integer


Steps:

 

  1. Declare prototype for the function named rec() used to calculate factorial value.
  2. Declare two integers a and fact.
  3. Prompt the message to enter any number to calculate the factorial.
  4. Allow the user to enter number using scanf().
  5. Use function rec() to calculate the factorial value using recursive method and return that.
  6. Print the returned value to the screen using printf() command. 

 


code:


#include <stdio.h>

int rec(int);
int main()
{
int a, fact;

printf("Enter any number");
scanf("%d",&a);

fact=rec(a);
printf("Factorial value-%d\n", fact);
return 0;
}

int rec(int x)
{
int f;

if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);

}






Related Posts:


468x60
معلومات عن التدوينة الكاتب : Unknown بتاريخ : الأربعاء، 9 يوليو 2014
المشاهدات :
عدد التعليقات: 0، للإبلاغ عن رابط معطوب اضغط هنا
250x300

شكرا لتعليقك
المتميز