Calculating Factorial

Ques: Write a C program to calculate the factorial of a non negative integer N. The factorial of a number N is defined as the product of all integers from 1 up to N. Factorial of 0 is defined to be 1. The number N is a non negative integer that will be passed to the program as the first command line parameter. Write the output to stdout formatted as an integer WITHOUT any other additional text. You may assume that the input integer will be such that the output will not exceed the largest possible integer that can be stored in an int type variable.


#include<stdio.h>
int main(int argc,char *argv[])
{
    int fact=1,i;
    if(argc!=2)
    {
      exit(1);
    }
    if(atoi(argv[1])<0)
        exit(1);
    if(atoi(argv[1])==0||atoi(argv[1])==1)
      fact=1;
    else
    {
        for(i=1;i<=atoi(argv[1]);i++)
        {
          fact=fact*i;
        }
    }
    printf("%d",fact);
    return 0;
}

Post a Comment

0 Comments