Buatlah fungsi faktorial secara rekursif untuk mencari n!.
n * faktorial (n-1)
C++ :
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int faktorial(int n){
if((n==0)or(n==1)) return(1);
else return(n*faktorial(n-1));
}
using namespace std;
int main(int argc, char** argv) {
int i,a;
cout<<"masukkan bilangan = ";cin>>a;
for(i=1;i<=a;i++)
cout<<"\n nilai"<<a<<"!= "<<faktorial(i);
return 0;
}
Analisis :
•Kasus penyetop (= nilai awal) n = 0 atau n = 1 yaitu bernilai konstan 1
•Kasus rekursif :
n * faktorial (n-1)
C++ :
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int faktorial(int n){
if((n==0)or(n==1)) return(1);
else return(n*faktorial(n-1));
}
using namespace std;
int main(int argc, char** argv) {
int i,a;
cout<<"masukkan bilangan = ";cin>>a;
for(i=1;i<=a;i++)
cout<<"\n nilai"<<a<<"!= "<<faktorial(i);
return 0;
}
Tidak ada komentar:
Posting Komentar