Sabtu, 09 April 2016

DIKTAT ALPRO BAB V latihan 2 (1-4)

BAB V
PERULANGAN/LOOP
(rekursif & iteratif)

 
1. Buatlah fungsi fibonacci dengan cara iteratif.
Program CPP :
#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
     int n, firstTerm = 1, secondTerm = 1, nextTerm;
    cout << "masukan nilai: ";
    cin >> n;

    cout << "urutan Fibonacci: " << firstTerm << " + " << secondTerm << " + ";
    nextTerm = firstTerm + secondTerm;

    while ( nextTerm < n) {
        cout << nextTerm << " + ";
        nextTerm = firstTerm + secondTerm;
        firstTerm = secondTerm;
        secondTerm = nextTerm;
    }
    return 0;
}
RAPTOR :
2. Buatlah fungsi fibonacci dengan 2 cara rekursif yang lain.
Program CPP :
 #include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
    int suku;
    int a,b,c;
     cout<<"Membuat Deret Fibonacci\n";
     cout<<"Masukkan nilai suku ke-: ";cin>>suku;

     cout<<"Bilangannya adalah: \n";
     a=0;b=1;
    cout<<a<<endl<<b<<endl;
     for(int i=3; i<=suku; i++)
    {
    c = a + b;
    a = b;
    b = c;

     cout<<c<<endl;
     }
    return 0;
}

RAPTOR :
3. Algoritma perkalian dengan cara penjumlahan pada algoritma 5.3. belum sempurna
karena belum mencakup semua kemungkinan, misalnya untuk harga b negatif.
Program CPP :
 #include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv)
{
    int a;
  
    for(a=1;a<=100;a++){
        if(a%3==0 && a%5==0){
            cout<<"bilangan habis di bagi 3 dan 5 = "<<a;
            cout<<endl;
          
        }else{
        }
    }
    return 0;
}

RAPTOR :


4. Buatlah program rekursif dari algoritma 5.3.
Program CPP :
#include <iostream>
#include<conio.h>
#include<math.h>
using namespace std;

    class hitung
    {
    public:
           void input();
           int proses();
    private:
            int a;
            float bil,hasil,total;
            };
  
    void hitung::input(){
    cin>>a;
    cout<<endl;}
  
    int hitung::proses(){
    hasil=0;
    total=0;
    bil=-1;
    for(int j=1; j<=a; j++){
    bil=(bil*(-1));
    total=bil/j;
    hasil+=total;
    if(j==1)
    cout<<"("<<bil<<"/"<<j<<")";
    if(j>1)
    cout<<" +("<<bil<<"/"<<j<<")";
    }
  
    cout<<endl<<endl<<"hasil penjumlahan deret = "<<hasil;
    return hasil;
    }
  
    int main()
    {
    cout<<"menghitung jumlah Hasil Deret 1-(1/2)+(1/3)-(1/4)+...+(1/n)"<<endl<<endl;
    cout<<"masukan nilai n : ";
    hitung deret;
    deret.input();
    deret.proses();
  
    getch();
    return 0;
    }

0 komentar

Posting Komentar