Factorial Calculator

If n is an integer greater than 0, n factorial (n!) is the product: n* (n-1) * (n-2) * ( n-3)… *

By convention, 0! = 1. You must write a program that allows a user to enter an integer between 1 and 7. Your program must then compute the factorial of the number entered by the user.

Your solution MUST actually perform a computation (i.e., you may not simply print “5040” to the screen as a literal value if the input is 7).

Example 1:
Enter a number: 4
4! = 24

Example 2:
Enter a number: 7
7! = 5040


Solution in C/C++:


#include <stdio.h>

int main ()
{
    printf ("Enter a number: ");

    int n;
    scanf ("%d", &n);

    int factorial = 1;
    for ( int i = 1; i <= n; i++ )
        factorial = factorial * i;

    printf ("%d! = %d\n", n, factorial );

    return 0;
}

Solution in Python:

import sys

sys.stdout.write ('Enter a number: ')

n = int (input ())
factorial = 1

for i in range (1, n + 1) :
    factorial *= i

print ('%d! = %d' % (n, factorial))

About Tausiq
Studying B.Sc in CSE (Computer Science and Engineering) United International University, Dhaka, Bangladesh.

4 Responses to Factorial Calculator

  1. JINI says:

    There are another way to solve this problem

    solution:

    #include <stdio.h>
    //#include
    
    int rec(int num);
    
    int main()
    {
        int number;
        int rezult;
        printf("Enter a number: ");
        scanf("%d",&number);
        rezult = rec(number);
        printf("%d! = %d\n",number,rezult);
        //system(“PAUSE”);
        return 0;
    }
    int rec(int num)
    {
        if(num == 1)
            return 1;
        /* else */
        return (num * rec(num-1));
    }
    
    
  2. shanto says:

    #include
    int func(int);
    int main()
    {int a,b,c,i;
    printf(“enter a number “);
    while(scanf(“%d”,&a)!=EOF)
    {
    c=func(a);
    printf(“%d!=%d”,a,c);
    }
    return 0;}
    int func(int a)
    {int b;
    if(a==1)
    return 1;
    else
    while(a!=1)
    {
    b=a*func(a-1);
    return b;
    }
    }

  3. OO says:

    May i have the problem number and problem site name. I couldn’t find any reference here.

  4. Tim says:

    Here is an example written in VB

    Console.Write(“Enter a number: “)
    Dim num As Integer = Console.ReadLine
    Dim total As Integer = num

    For i As Integer = 1 To num – 1
    total = total * (num – i)
    Next

    Console.WriteLine(total.ToString)
    Console.ReadLine()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 48 other followers