latest Post

Program fibonacci rekursif dan iterative dengan validasi di C++




#include <iostream>
#include <math.h>
#include <limits>
#include <cstdlib>
#include <cstring>
using namespace std;

int kata;
char val [100];

int validasi()
{
    do
    {
        kata=0;
        cout<<"\t\t";cin>>val;
        for(int i=0; i<strlen(val); i++)
        {
            if(isdigit(val[i])==0)
                kata++;
        }
        if(kata !=0)
            cout<<"\t\tInput salah !\n"<<endl;

    }
 while(kata!=0);
    return 0;
}


int fibo(int bil){
 if(bil==0) return 0;
    else if(bil==1) return 1;
    else return fibo(bil-1)+fibo(bil-2);
}

int iteratif (int suku) {
 int a=0, b=1,c; 
 if(suku==0) return 0;
   for(int i=1; i<=suku; i++){ 
    c = a + b; 
    b = a;
    a = c;
    cout<<"\t\t"<<c<<"\n"; 
   }
   return c;
  }

int main(){
      int bil,pilihan;
      
      cout<<"\tFungsi Rekursif dan Iterative Bilangan Fibonacci"<<endl;
      cout<<"\t================================================"<<endl; 
   cout<<"\t\tTekan 1 untuk Fibonacci Rekursif\n\t\tTekan 2 untuk Fibonacci Iterative\n\t\tTekan 3 untuk Berehenti"<<endl;
   
   balik:
   cout<<"\n\t\tMasukkan Pilihan : ";
   validasi(); pilihan=atoi(val);
   
   switch(pilihan){
   
   case 1 : {
    cout<<"\n\t\tFibonacci Rekursif ";
    cout<<"\n\t\tMasukkan bilangan : ";
     validasi(); bil=atoi(val);
     if (bil<0)
   cout<<"\t\tNilai harus berupa bilangan bulat positif";
  else{
   for (int i=1;i<=bil;i++){
    cout<<"\t\t"<<fibo(i)<<"\n"; 
   }
   
   cout<<"\t\tFibonacci("<<bil<<") = "<<fibo(bil);
   
  }
  break;
  }  
      
   case 2 :{
    int suku;
    cout<<"\n\t\tFibonacci Iterative ";
   cout<<"\n\t\tMasukkan bilangan : ";
   validasi(); suku=atoi(val);
   if (suku<0)
    cout<<"\t\tNilai harus berupa bilangan bulat positif";
   else 
    cout<<"\t\tFibonacci("<<suku<<") = "<<iteratif ( suku); 
  break;
   }   
   
   case 3:{
    cout<<"\t\tBye ";
    return 0;
   }
    
   default :
    cout<<"\t\tPilihan salah !";
   
   }
   
 cout<<"\n\t------------------------------------------------"<<endl; 
 system("pause");
 goto balik;
      
}




About Unknown

Unknown
Recommended Posts × +

0 comments:

Post a Comment