Friday, 20 February 2015

Factorial Of A Number in C

Write A Program to Find Factorial Of A Number

Problem Can Be Solved Using 

1. Recursion

#include<stdio.h>
int fact(int num){
if((num == 0)||(num == 1))
return 1;
else
return num*fact(num-1);
}
int main(int argc, char *argv[]){
int num;
num = atoi(argv[1]);
printf("%d!=%d\n",num,fact(num));
return 0;
}
Compiling and Running Under Linux

rajesh@ThinkPad:~/Rajesh/blogs$ gcc factorial.c -o factnum
rajesh@ThinkPad:~/Rajesh/blogs$ ./factnum 4
4!=24
rajesh@ThinkPad:~/Rajesh/blogs$ ./factnum 5
5!=120
rajesh@ThinkPad:~/Rajesh/blogs$ ./factnum 6
6!=720

2. Using Loop

#include<stdio.h> 
int fact(int num){
int res;
res=1;
while(num){
res*=num;
num--;
}
return res;
}
int main(int argc, char *argv[]){
int num;
num = atoi(argv[1]);
printf("%d!=%d\n",num,fact(num));
return 0;
}
Compiling and Running Under Linux

rajesh@ThinkPad:~/Rajesh/blogs$ gcc factorial.c -o factnum
rajesh@ThinkPad:~/Rajesh/blogs$ ./factnum 4
4!=24
rajesh@ThinkPad:~/Rajesh/blogs$ ./factnum 5
5!=120
rajesh@ThinkPad:~/Rajesh/blogs$ ./factnum 6
6!=720

No comments:

Post a Comment