Senin, 18 April 2011

Perulangan Rekursif

#include <iostream.h>

class Deret {
    friend istream& operator>>(istream&, Deret&);
    friend ostream& operator<<(ostream&, Deret&);
public:
    long hitung(int);
    void cetak(int);
private:
    int suku_n;
    long hasil;

};

long Deret::hitung(int n) {
    if (n==1) return 1;
    else return n+hitung(n-1);
}

void Deret::cetak(int n) {
    if (n>0) {
        cetak(n-1);
        cout << "Suku ke : " << n << " = " << hitung(n) << endl;
    }
}

istream& operator>>(istream& input, Deret& x) {
    cout << "Masukkan integer : ";
    input >> x.suku_n;
    return input;
}

ostream& operator<<(ostream& output, Deret& x) {
    output << "Jumlah Deret : ";
    for (int i=1; i<= x.suku_n; i++)
        if (i == x.suku_n)
            cout << i << " adalah " << endl;
        else cout << i << " + ";
    x.cetak(x.suku_n);
    return output;
}

void main() {
    Deret Bilangan;
    cin >> Bilangan;
    cout << Bilangan << endl;
}

0 komentar:

Posting Komentar

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Blogger Theme by Lasantha - Premium Blogger Templates | Affiliate Network Reviews