C++ or C program to calculate factorial of number N using Recursion/ Recursive Function.

File name:- factrec.cpp
#include<iostream.h>
#include<conio.h>
//recursive function of factorial
long factorial(long f){
if(f==1) return 1;
return f*factorial(f-1);
}
void main(){
long fact=1,n;
clrscr();
cout<<"Enter a positive integer number"<<endl;
cin>>n;
if(n>0){
fact=factorial(n);
cout<<"Factorial of "<<n<<" = "<<fact<<endl;
}
else 
cout<<"Wrong number inserted"<<endl;
getch();
}

File name:- factrec.c
#include<stdio.h>
#include<conio.h>
//recursive function of factorial
long factorial(long f){
if(f==1) return 1;
return f*factorial(f-1);
}
void main(){
long fact=1,n;
clrscr();
printf("Enter a positive integer number\n");
scanf("%ld",&n);
if(n>0){
fact=factorial(n);
printf("Factorial of %ld = %ld\n",n,fact);
}
else{
printf("Wrong number inserted\n");
}
getch();
}

No comments:

Post a Comment

Stack Data Structure, Push, Pop and Peek Operations , Applications of Stack

Stack is a linear data structure. It is collection of ordered data elements. It is also known as LIFO system (last in first out). It means i...