Adsense 728 * 15

Search

Custom Search

C,C++ Program to Print Factorial of a Number


Write a C,C++ program to print  factorial of a number. In this program i'll write iterative code to print factorial of a number. You can check how to print factorial of a number using recursion.

Difference between iteration and recursion.

For any input number n, it's factorial is

factorial = 1 * 2 * 3 * 4 .......n;


C++ Code to Print factorial of a number




#include<iostream.h>

int main() 
{

 int number,fact=1;  //Variable declared

 cout<<"Enter the number: "; 
 cin>>number;

 if(number > 0) {
   for(int i=1;i<=number;i++){
    fact=fact*i;                  
  }

  cout<<"The factorial of a number is: "<<fact;
 
  } else if (number == 0 ){

  cout << "Factorial of 0 is 1";

  } else {

   cout<< " Factorial of a negative number doesn't exist";
} return 0; }

C Code to print factorial of a number



#include<stdio.h>

int main() 
{

 int number,fact=1,i;  //Variable declared

 printf("Enter the number: "); 
 scanf("%d",&number);
 
 if(number > 0) {

   for(i=1;i<=number;i++){
     fact=fact*i;                  
  }

  printf("The factorial of a number is: %d",fact);
 
  } else if (number == 0 ){

  printf("Factorial of 0 is 1");

 } else {

 printf("Factorial of negative number doesn't exist";
 
  }
 return 0;
 }

No comments:

Post a Comment