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. Repeat FOR i = num to 1 by -1
    • fact = fact * i.
    • Write “i *”.
    • [End of FOR loop.]
  5. Write “= fact”.
  6. Exit.

Flowchart

C++ Source Code

// program 37
#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";
  for (i = num; i >= 1; i--)
  {
    fact = fact * i;
    cout << i;
    if (i != 1)
    cout << " * ";
  }
  cout << " = " << fact;
  return 0;
}

C Source Code

/*program 37*/
#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);
  for(i=num; i>=1; i--)
     {
     fact = fact * i;
     printf("%d * ", i);
     }
  printf("\b\b= %d", fact);
  return 0;
}

Output

Enter any number: 7

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

Design a site like this with WordPress.com
Get started