Laman

Minggu, 08 April 2012

Fungsi Rekursif

Faktorial.java


public class soal_1 {
    public int faktorial( int n )
    {
        if( n <= 0 )
            return 1;
        else
            return n * faktorial( n - 1 );
    }
}



FaktorialApp.java


public class soal_1_App {
    public static void main(String[] args){
        soal_1 F = new soal_1();
        int bil1=Integer.parseInt(JOptionPane.showInputDialog("Masukkan Bilangan 1"));
        int bil2=Integer.parseInt(JOptionPane.showInputDialog("Masukkan Bilangan 2"));
        int a =F.faktorial(bil1);
        int b =F.faktorial(bil2);
        System.out.println("Bilangan-1 = "+bil1+" faktorial = "+a);
        System.out.println("Bilangan-2 = "+bil2+" faktorial = "+b);
        System.out.println("Kurang >>> "+(a-b));
        System.out.println("Tambah >>> "+(a+b));
        System.out.println("Kali >>> "+(a*b));
    }
}


Fibonaci.java

public class soal_2 {
    public int fibo(int n) {
        if (n <= 1)
  return n;
        else
  return fibo(n-1) + fibo(n-2);
    }
}

FibonaciApp.java

public class soal_2_App {
    public static void main(String[] args){
        soal_2 F = new soal_2();
        int suku=Integer.parseInt(JOptionPane.showInputDialog("Masukkan Suku ke-n"));
        System.out.println("Suku Sfibonaci ke-"+suku+" = "+F.fibo(suku-1));
    }
}

Tidak ada komentar:

Posting Komentar