Kasus 5.4
Buatlah fungsi perkalian 2 bilangan bulat dengan menggunakan operator penjumlahan.
Analisis :
•Misalkan a dikalikan b (input)
•Proses :
a x b = a + a + a + … + a (sebanyak b kali)
C++ :
#include <iostream>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int kali(int g, int h){
int i, hasil=0;
for(i=1; i<=h; i++)
hasil +=g;
if(h<0) return(-hasil); else return(hasil);
}
int main(int argc, char** argv) {
cout<<"menghitung hasil perkalian\n";
int x,y;
cout<<"masukkan bil-1 = "; cin>>x;
cout<<"masukkan bil-2 = "; cin>>y;
cout<<x<<" x "<<y<<" = "<<kali(x,y);
return 0;
}
Kalau di run, hasilnya :
Raptor :
Kasus 5.5
Buatlah fungsi faktorial secara rekursif untuk mencari n!.
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;
}
Kalau di run, hasilnya :
Raptor :
Untuk Kasus 5.2 dan 5.3, dapat dilihat di : http://hiwilmacleta.blogspot.co.id/search/label/TugasKe4
Untuk Kasus 5.2 dan 5.3, dapat dilihat di : http://ratihpuspita29.blogspot.co.id/search/label/tugas5








Tidak ada komentar:
Posting Komentar