Object

Write a program which reads a number and prints its factorial.

Algorithm

  1. Declare integer variables num, i and fact.
  2. Set fact = 1.
  3. Read num.
  4. Set i = num.
  5. Repeat WHILE i >= 1
    • fact = fact * i.
    • Write “i *”.
    • i–.
    • [End of WHILE loop.]
  6. Write “= fact”.
  7. Exit.

Flowchart

C++ Source Code

// program 52
#include<iostream>
using namespace std;

int main()
{
  int num, i, fact = 1;
  cout << "Enter any number: ";
  cin >> num;
  cout << "\nThe factorial of number " << num << " is\n";
  i = num;

  while (i >= 1)
  {
    fact = fact * i;
    cout << i << " * ";
    i--;
  }
  cout << "\b\b= " << fact;
  return 0;
}

C Source Code

/*program 52*/
#include<stdio.h>

int main()
{
  int num, i, fact=1;
  printf("Enter any number: ");
  scanf("%d", &num);
  printf("\nThe factorial of number %d is\n", num);
  i = num;
  while(i>=1)
     {
     fact = fact * i;
     printf("%d * ", i);
     i--;
     }
  printf("\b\b= %d", fact);
  return 0;
}

Output

Enter any number: 6

The factorial of number 6 is
6 * 5 * 4 * 3 * 2 * 1 = 720

Design a site like this with WordPress.com
Get started