Kamis, 21 April 2011

Konversi dari function iteratif ke rekursif


Versi iteratif :

Fungsi pangkat (input x,y : integer) : integer
Deklarasi :
x,y : integer
Deskripsi :
   pangkat
<= 1
   for i 1
<= to y do
       pangkat
รง pangkat * x

#include <iostream.h>
#include <conio.h>

class hitung{
   public :
   void pangkat();

   private :
      int x, y;
      int hasil;
};

void hitung::pangkat(){
   cout<< "Masukan nilai :";
   cin>>x;
   cout<< "Mau dipangkat berapa : ";
   cin>>y;
   hasil=1;
   for(int i=1;i<=y;i++){
      hasil=hasil*x;
   }
   cout <<"Maka hasilnya adalah : "<< hasil << endl;
}

int main(){
   hitung a;
   a.pangkat();
   return 0;
}

Versi Rekursif :

Rekursif :
Fungsi pangkat(input x,y : integer) : integer
if (y=1) then
 pangkat <= 1
x pangkat y <= x.x pangkat (y-1)
pangkat(x,y) <= x.pangkat(x,y-1)


#include <iostream.h>
#include <conio.h>

int pangkat(int x, int y){
 if (y==1)
   return x;
 else
   return x* pangkat(x, y-1);
}

int main(){
int x, y;
 int hasil;
 cout << "Menghitung x pangkat y\n";

 cout<< "Masukan nilai :";
 cin>> x;
 cout<< "Mau dipangkat berapa :";
 cin>> y;

   hasil = pangkat (x,y);
   cout << "Maka hasilnya adalah :"<<hasil;
   return 0;
}

tracing : (input x=2, y=3)
x is 2                                                     x is 2                                                  x is 2
y is 3                                  = 8              y is 2                                  = 4            y is 1              = 2
3 == 1 is false                  ------------->   2==1 is false                ---------------> 1==1 is true  -----------
ans is 7 ^ power 2,2                                ans is 2 ^ power (2,1)                            ans is 2
Return (ans)                                           return (ans)                                          return (ans)

Analysis:
This program contains the count powers of x and y (x ^ y) and in the iterative loop using a loop function for and starts at a to-1. Each iteration x will be multiplied by y after that iteration will be terminated.
While his recursive function to replace the loop with mathematical formulas that take 1 dr recursive formula to x and the rest of the tribe is using the same formula with the original formula.

In his program above formula is x * power (x, y-1) of the original formula xxx y times and in the recursion formula should be a condition to stop looping and conditions when y = 1, or can be written in the program if (y == 1) return x; which is useful for menghetikan looping / shut-off and mereturn his value x.


 


0 komentar:

Posting Komentar

Template by:

Free Blog Templates