Exercise pertemuan 1 sampai 4


Pertemuan 1 Exercise

  • Write a C++ program that searches an unsorted array a[0:n-1] for the element x. If x exists in the array then return a position in the array, else return -1.

Answer :

#include<iostream>
using namespace std;

int linearSearch(int a[], int key, int size){
int n;
for (n=0; n < size; ++n){
if (a[n] == key){
return n;
}
}
return -1;
}

int main(){
int a[100], counter=0, total, i, search;
cout<<“Banyak angka yang ingin diinput: “;
cin>>total; cin.sync();cin.clear();
cout<<“Type each of “<<total<<” int now, each seperated by ENTER: “<<endl;
for(i=0;i<total;i++){
cin>>a[i];
cin.sync();
cin.clear();
}
cout<<“Now enter the int to search: “<<endl;
cin>>search;
cin.sync();
cin.clear();
cout<<linearSearch(a,search,total);
cin.get();
return 0;
}

  • The factorial function n! has value 1 when n   1 and value n*(n-1)! When n>1. Write both a recursive and an iterative C++ program to compute n!

Recursive :

#include<iostream>
using namespace std;

int faktorial(int n){
if(n < 1){
return 1;
}
else{
return n * faktorial(n-1);
}
}

int main(){
int n;
cin >> n;
cin.sync();
cin.clear();
faktorial(n);
cout << faktorial(n);
cin.get();
return 0;
}

Iterative :

#include<iostream>
using namespace std;

void main()
{
int i, N, iTampung=1;
cin>>N;cin.sync();cin.clear();
for(i=1; i<=N; i++){
iTampung = iTampung * i;
}
cout<<“Faktorial dari “<<N<<” adalah “<<iTampung;
cin.get();
}

  • Consider the function F(x) defined by “if x is even then F(x)=x/2; else F(x)=F(F(3x+1)).” Prove that F(x) terminates all integer x.

#include<iostream>
using namespace std;

int f(int x){
return x/2;
}

int main(){
int angka;
cin>>integer; cin.clear(); cin.sync();
if(integer%2 == 0){
cout<<f(angka);
}
else{
cout<<f(f(3*angka+1));
}
cin.get();
return 0;
}

  • Buatlah pseudocode untuk menghitung jumlah N bilangan ganjil yang pertama dengan menggunakan teknik rekursif!

Module jumlah(N)
if N == 1 then
result = 1
else
result = ( 2*N-1 ) + jumlah( N-1 )
end if
end module

  • Hitunglah Fungsi Kompleksitas untuk algoritma bilangan Fibonacci yang terdapat di pertemuan sebelumnya!

f1=0   (1)
f2=1   (1)
for i=1 to 8 do  (N)
iFibo=f1+f2 (N)
display ”Angka ke-”,i,” adalah ”,iFibo,NL(N)
f1=f2  (N)
f2=iFibo     (N)
end for

Fungsi Kompleksitas f(N) : 5N + 2

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.