M3-R4: January 2013 (O-Level)
Q. 9(b):
Write a ‘C’ program to find out a factorial of a given number?
Ans:
Method 1: Finding factorial using loop:
#include <stdio.h>
#include <conio.h>
void main(){
int num, i;
long fact = 1;
printf("\nEnter an integer: ");
scanf("%d", &num);
for(i=num; i>0; i--){
fact = fact * i;
}
printf("\n%d! = %ld", num, fact);
getch();
}
Method 2: Finding factorial using recursive function:
#include <stdio.h>
#include <conio.h>
long fact(int);
void main(){
int num;
long f;
printf("\nEnter an integer: ");
scanf("%d", &num);
f = fact(num);
printf("\n%d! = %ld", num, f);
getch();
}
long fact(int n){
if(n <= 0)
return 1;
return n * fact(n-1);
}
Q. 9(b):
Write a ‘C’ program to find out a factorial of a given number?
Ans:
Method 1: Finding factorial using loop:
#include <stdio.h>
#include <conio.h>
void main(){
int num, i;
long fact = 1;
printf("\nEnter an integer: ");
scanf("%d", &num);
for(i=num; i>0; i--){
fact = fact * i;
}
printf("\n%d! = %ld", num, fact);
getch();
}
Method 2: Finding factorial using recursive function:
#include <stdio.h>
#include <conio.h>
long fact(int);
void main(){
int num;
long f;
printf("\nEnter an integer: ");
scanf("%d", &num);
f = fact(num);
printf("\n%d! = %ld", num, f);
getch();
}
long fact(int n){
if(n <= 0)
return 1;
return n * fact(n-1);
}
No comments:
Post a Comment