C program to find the factorial of a number - wordsclank.in

Saturday 3 March 2018

C program to find the factorial of a number

Before we start coding lets have a brief look on what factorial really means.?
The factorial of a integer n is nothing but the product of the integer and all the integer below it.
For example n!=(n)*(n-1)*(n-2)...*2*1
 or, n!=1*2*3*4....(n-1)*n
note that 0!=1
wordsclank.bmlogspot.co





SOURCE CODE


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<stdio.h>
void main()
{
 int i, num;
 int factorial;
 
 printf("Enter the integer :\n");
 scanf("%d",&num);
 if(num > 0)
 {
  for(i = 1; i <= num; i++)
  {
   factorial = factorial * i;
  }
  printf("The factorial of %d is %d",num,factorial);
 }
 else if(num == 0)
 {
  printf("The factorial of %d is 1",num,factorial);
  //0! is always 1
 }
 else
 {
  printf("Error! Negative number's factorial doesnt exist. Enter a positive number:\n");
  //error message for user for entering negavitive number
 }
 
}

OUTPUT


wordsclank.blogspot.com

Explanation

Within the main function first we declared three integer variable i , n and factorial . Next we display a message to take input from the user and store it to the integer variable n.Next we use a if -else conditional checking that will check the number as positive or negative. If the number is negative then it will display a  message that "Error! Negative number's factorial doesn't exist. Enter a positive number:".And if the number is positive it will continue.Then under the for loop it will multiply number and numbers below it one by one and store it in factorial integer variable.when the controls comes out of the loop then it will display it.
I

Related Topics



No comments:

Post a Comment