Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS151 / KCS251 Programming for Problem Solving - Using C Language
Lab Exercises
17. Write a program to calculate the factorial for the given number using a function.
/*
File: Prgrm17.c
Author: Aditya Saini
Date: Jan 17, 2021
Description: Program to calculate the factorial for the given number using a function.
*/
#include <stdio.h>
int factorial (int);
int main (void)
{
int num;
int fact;
//Input number
printf ("Input number: ");
scanf ("%d", &num);
//Function call
fact = factorial (num);
//Print result
if (fact > 0)
{
printf ("Factorial: %d", fact);
}
};
int factorial (int num)
{
int fact;
int i;
//Calculate factorial
fact = 1;
if (num >= 0)
{
for (i = 1; i <= num; i++)
fact = fact * i;
return fact;
}
else
{
printf ("Error! Negative number");
return -1;
}
};
Output
Input number: 5
Factorial: 120
No comments:
Post a Comment
Please do not post spam links.