C Program to find the factorial of a given number - Online Judge Solution

Latest

It is a free Online judges problems solution list. Here you can find UVA online Judge Solution, URI Online Judge Solution, Code Marshal Online Judge Solution, Spoz Online Judge Problems Solution

Thursday, November 30, 2017

C Program to find the factorial of a given number

C Program to find the factorial of a given number


Problem:
Write a C program that will get the factorial of the given number.

Solution:

Logic to make a factorial number:

C Program to find the factorial of a given number


That means, take a number and multiply every number upto one.
In programming, take a simple for loop or while loop. Multiply and add the number from one to that number.

C Code for factorial number:

#include <stdio.h>
 
int main()
{
  int i, n, fact = 1;
 
  printf("Enter a number to find it's factorial = \n");
  scanf("%d", &n);
 
  for (i = 1; i <= n; i++)
    fact = fact * i;
 
  printf("Factorial of %d = %d\n", n, fact);
 
  return 0;
}


Run Code: [Give input as your wish like 5... output will be 120]



Now Get more perfect code for long number factorials

C Code for factorial number:

Problem of previous code was it can't return a large  numbers factorial. That return a furbage value. So, to get a better result just use this code to find factorial in c.

#include <stdio.h>
int main()
{
    int n, i;
    unsigned long long factorial = 1; //take long integer to get a big factorial

    printf("Enter an integer: ");
    scanf("%d",&n);

    // show error if the user enters a negative integer
    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");

    else
    {
        for(i=1; i<=n; ++i)
        {
            factorial *= i;              // factorial = factorial*i;
        }
        printf("Factorial of %d = %llu", n, factorial);
    }

    return 0;
}


Tags:
C Program to find the factorial of a given number, Factorial solution, factorial demonstration, how to find a factorial, factorial c code, code factorial

No comments:

Post a Comment