116 CONTOH PROGRAM PADA C++ (TERLENGKAP)
116 CONTOH PROGRAM PADA C++ (TERLENGKAP)
1. CONTOH PROGRAM MENGGUNAKAN GETLINE (STRING)
#include <iostream>#include <string>
using namespace std;
int main()
{
string mystr;
cout<<"What's Your Name? ";
getline(cin, mystr);
cout<<"Hello "<<mystr<<". \n";
cout<<"What Is Your Favorite Team ? ";
getline(cin, mystr);
cout<<"I Like "<<mystr<<"too! \n";
return 0;
}
2. CONTOH PROGRAM PENGGUNAAN GETLINE (CONVERSI KE INTEGER)
#include <iostream>#include <string>
#include <sstream>
using namespace std;
int main()
{
string mystr;
float price=0;
int quantity=0;
cout<< "Enter Price: ";
getline(cin, mystr);
stringstream(mystr)>>price;
cout<<"Enter Quantity: ";
getline(cin, mystr);
stringstream(mystr)>>quantity;
cout<<"Total Price : "<<price*quantity<<endl;
return 0;
}
3. CONTOH PROGRAM PENGGUNAAN MYSTREAM
#include <iostream>#include <sstream>
using namespace std;
int main()
{
stringstream my_stream (ios::in|ios::out);
std::string dat ("Hey, I have a double : 74, 79 . ");
my_stream.str(dat);
my_stream.seekg(-7,ios::end);
double val;
my_stream>>val;
val=val*val;
my_stream.seekp(-7,ios::end);
my_stream<<val;
std::string new_val = my_stream.str();
cout<<new_val;
return 0;
}
4. CONTOH PROGRAM PENGGUNAAN CHAR ARRAY
#include <iostream>using namespace std;
int main()
{
char str[] = "Unable to read....";
clog<<"Error message : "<<str<<endl;
}
5. CONTOH PROGRAM PENGGUNAAN SETBASE
#include <iostream>using namespace std;
int main()
{
int a=160;
cout <<"Octal Base "<<setbase(8)<<a<<endl;
cout <<"Decimal Base "<<setbase(10)<<a<<endl;
cout <<"Hexadecimal Base "<<setbase(16)<<a<<endl;
return 0;
}
6. CONTOH PROGRAM PENGGUNAAN FUNGSI SETW
#include <iostream>using namespace std;
int main()
{
cout <<"123456789"<<endl;
cout<<setw (9)<<"x"<<endl;
return 0;
}
7. CONTOH PROGRAM MENGHITUNG BILANGAN GENAP SAMPAI ANGKA TERTENTU
#include <iostream>using namespace std;
int main(){
int n, jumlah=0, bil, i=1;
cout << "masukan banyaknya jumlah bilangan" << endl;
cin >> n;
cout << "masukan bilangan: ";
do{
cin >> bil;
if(bil%2==0){
jumlah=jumlah+bil;
}
i++;
}while(i<=n);
cout << "jumlah bilangan genap: " << jumlah;
return 0;
}
8. CONTOH PROGRAM MENGHITUNG NILAI RATA-RATA MAHASISWA DENGAN WHILE
#include<iostream>using namespace std;
int main(){
int nilai, jumlahnilai=0, n, m, i=1, x=1,rata;
string nama;
cout << "masukan jumlah mahasiswa: " << endl;
cin >> n;
cout << "masukan jumlah matakuliah: " << endl;
cin >> m;
do{
cout << "Nama mahasiswa: " << endl;
cin >> nama;
cout << "Masukan nilai mahasiswa: " << endl;
do{
cin >> nilai;
jumlahnilai=jumlahnilai+nilai;
i++;
}while(i<=m);
rata=jumlahnilai/m;
cout << "rata rata nilai mahasiswa: " << rata << endl;
i=1;
jumlahnilai=0;
x++;
}while(x<=n);
return 0;
}
9. CONTOH PROGRAM PENGECEKAN SANDI SEDERHANA
#include <iostream>#include <string>
using namespace std;
int main()
{
const string sandi="abcdef";
string pw;
bool sah;
int k;
k=1;
sah=false;
do
{
cout<<"Masukkan kata sandi : ";
cin>>pw;
if(pw==sandi)
{
sah=true;
cout<<"Kata sandi benar,bernilai "<<sah;
break;
}
else
{
cout<<"Kata sandi salah ulangi lagi,bernilai "<<sah<<endl;
k=k+1;
}
}
while(k<=3);
}
10. CONTOH PROGRAM PENGGUNAAN SWITCH CASE
#include <iostream>using namespace std;
int main()
{
int n,usia;
int usia15,usia16,usia17,usia18,lainnya;
int i;
cout<<"Masukkan Banyak Siswa :";
cin>>n;
usia15=0;
usia16=0;
usia17=0;
usia18=0;
lainnya=0;
i=1;
while(i<=n)
{
do
{
cout<<"Masukkan Usia :";
cin>>usia;
switch(usia)
{
case 15:
usia15=usia15+1;
break;
case 16:
usia16=usia16+1;
break;
case 17:
usia17=usia17+1;
break;
case 18:
usia18=usia18+1;
break;
default:
lainnya=lainnya+1;
break;
}
i=i+1;
}
while(i<=n);
cout<<"Jumlah siswa usia 15 tahun adalah "<<usia15<<endl;
cout<<"Jumlah siswa usia 16 tahun adalah "<<usia16<<endl;
cout<<"Jumlah siswa usia 17 tahun adalah "<<usia17<<endl;
cout<<"Jumlah siswa usia 18 tahun adalah "<<usia18<<endl;
cout<<"Jumlah siswa usia selain 15-18 tahun adalah "<<lainnya;
}
}
11. CONTOH PROGRAM UNTUK MENUNJUKKAN UKURAN BIT DATA
#include <iostream>using namespace std;
int main()
{
cout<<"Size Of char : "<<sizeof(char)<<endl;
cout<<"Size Of int : "<<sizeof(int)<<endl;
cout<<"Size Of short int : "<<sizeof(short int)<<endl;
cout<<"Size Of long int : "<<sizeof(long int)<<endl;
cout<<"Size Of float : "<<sizeof(float)<<endl;
cout<<"Size Of double : "<<sizeof(double)<<endl;
cout<<"Size Of wchar_t : "<<sizeof(wchar_t)<<endl;
return 0;
}
12. CONTOH PROGRAM OPERASI ARITMATIKA SEDERHANA
#include <iostream>using namespace std;
int main()
{
int a=5;
int b=(3);
int c{2};
int result;
a= a+b;
result = a - c;
cout<<result;
return 0;
}
13. CONTOH PROGRAM MENAMPILKAN KATA SEDERHANA (STRING)
#include <iostream>#include <string>
using namespace std;
int main()
{
string mystring;
mystring = "this is the initial string content";
cout<<mystring<<endl;
mystring = "this is a different string content";
cout<<mystring<<endl;
return 0;
}
14. CONTOH PROGRAM MENGHITUNG KELILING LINGKARAN DENGAN KONSTANTA
#include <iostream>using namespace std;
const double pi = 3.14159;
const char newline = '\n';
int main()
{
double r=5.0; // radius
double circle;
circle = 2 * pi * r;
cout<<circle;
cout<<newline;
}
15. CONTOH PROGRAM MENHITUNG LUAS PERSEGI DENGAN KONSTANTA
#include <iostream>using namespace std;
int main()
{
const int side=50;
int area;
area = side * side;
cout<<"The area of the square with side : " << side<<" is: "<<area;
return 0;
}
16. CONTOH PROGRAM MENGHITUNG LUAS LINGKARAN DENGAN DEFINE
#include <iostream>using namespace std;
#define pi 3.14159
#define newline '\n'
int main()
{
double r=5.0;
double circle;
circle = 2 * pi * r;
cout<<circle;
cout<<newline;
}
17. CONTOH PROGRAM SIGNED DAN UNSIGNED INTEGER
#include <iostream>using namespace std;
/* This program shows the
* signed and unsigned int
*/
int main()
{
short int i;
short unsigned int j;
j=50000;
i=j;
cout<<i<<" "<<j;
return 0;
}
18. CONTOH PROGRAM PENGGUNAAN SHORTHAND SSIGNMENT OPERATOR
#include <iostream>using namespace std;
int main()
{
int a, b=3;
a=b;
a+=2;
cout<<a;
return 0;
}
19. CONTOH PROGRAM PENGGUNAAN OPERATOR RELASI
#include <iostream>using namespace std;
int main()
{
int a, b, c;
a=2;
b=7;
c=(a>b)? a: b;
cout<<c<<'\n';
return 0;
}
20. CONTOH PROGRAM MENGHITUNG LUAS PERSEGI PANJANG MENGGUNAKAN DEFINE
#include <iostream>using namespace std;
#define length 10
#define width 5
#define newline '\n'
int main()
{
int area;
area = length * width;
cout<<area;
cout<<newline;
return 0;
}
21. CONTOH PROGRAM PENGGUNAAN INCREMENT SEDERHANA
#include <iostream>using namespace std;
int main()
{
int c; //mendeklarasikan variabel c
//mengisikan nilai ke dalam variabel c dengan nilai 5
c=5;
//melakukan pre-increment
cout<<"Nilai C awal : "<<c<<endl;
cout<<"Nilai ++C : "<<++c<<endl;
cout<<"Nilai C akhir : "<<c<<endl;
cout<<'\n';
//mengubah nilai yang terdapat dalam variabel c dengan nilai 10
c=10;
//melakukan post increment
cout<<"Nilai C awal : "<<c<<endl;
cout<<"Nilai ++C : "<<++c<<endl;
cout<<"Nilai C akhir : "<<c<<endl;
return 0;
}
22. CONTOH PROGRAM PENGGUNAAN OPERATOR RELASI SEDERHANA
#include <iostream>using namespace std;
int main()
{
int x=5;
int y=7;
if(!x==y)
cout<<"x does not equal y";
else
cout<<"x equals y";
return 0;
}
23. CONTOH PROGRAM PENGGUNAAN TIPE DATA BOOLEAN
#include <iostream>using namespace std;
int main()
{
bool a = true;
bool b = false;
bool c = true;
cout<<"(a && b) : "<< (a&&b);
cout<<"\n (a && c) : "<< (a&&c);
cout<<"\n (a && b && c) : "<< (a&&b&&c);
cout<<"\n (a || b) : "<< (a||b);
cout<<"\n (a || c) : "<< (a||c);
cout<<"\n (a || b || c) : "<<(a||b||c);
cout<<"\n !a : "<< !a;
cout<<"\n !b : "<< !b;
cout<<"\n !c : "<< !c;
cout<<"\n !(b && a) : "<<!(b&&a);
//getch
}
24. CONTOH PROGRAM MENGHITUNG LUAS PERMUKAAN DAN VOLUME KERUCUT, BOLA DAN LIMAS DENGAN IF
#include <iostream>using namespace std;
int main()
{
int pil;
float p1, p2, l1, l2, t1, t2, t3, r1, r2;
float v, lp,v_kerucut, v_bola, v_limas;
float phi=3.14159;
//p1 = panjang balok, p2= panjang alas limas
//t1=tinggi balok, t2 tinggi kerucut, t3 = tinggi limas
//r1=jari jari kerucut, r2=jari-jari bola
//proses input p,l,t
cout<<"Daftar Paket Program Program :";
cout<<"\n 1. Menghitung Volume dan Luas Permukaan Balok";
cout<<"\n 2. Menghitung Volume Kerucut";
cout<<"\n 3. Menghitung Volume Bola";
cout<<"\n 4. Menghitung Volume Limas";
cout<<"\n Masukkan Nomor Pilihan = ";
cin>>pil;
if(pil=1){
cout<<"\n ===================================";
cout<<"\n Masukkan nilai panjang balok = ";
cin>>p1;
cout<<"\n Masukkan nilai lebar balok = ";
cin>>l1;
cout<<"\n Masukkan nilai tinggi balok = ";
cin>>t1;
//Balok p1 l t1 v lp
v=p1*l1*t1;
lp=(2*p1*l1)+(2*p1*t1)+(2*l1*t1);
cout<<"\n ===================================";
cout<<"\n Volume balok = "<<v;
cout<<"\n Luas permukaan balok = "<<lp;
}
else if(pil=2){
cout<<"\n ===================================";
cout<<"\n Masukkan nilai jari-jari kerucut = ";
cin>>r1;
cout<<"\n Masukkan nilai tinggi kerucut = ";
cin>>t2;
//kerucut r1, t2 v_kerucut
v_kerucut = ( phi * r1 * r1 * t2 )/3 ;
cout<<"\n ===================================";
cout<<"\n Volume kerucut = "<<v_kerucut;
}
else if(pil=3){
cout<<"\n ===================================";
cout<<"\n Masukkan nilai jari-jari bola = ";
cin>>r2;
//bola r2, v_bola
v_bola = (4 * phi * r2 * r2 * r2 )/3 ;
cout<<"\n ===================================";
cout<<"\n Volume bola = "<<v_bola;
}
else
{
cout<<"\n ===================================";
cout<<"\n Masukkan nilai panjang alas limas = ";
cin>>p2;
cout<<"\n Masukkan nilai lebar alas limas = ";
cin>>l2;
cout<<"\n Masukkan nilai tinggi limas = ";
cin>>t3;
//limas p2, l2, t3, v_limas
v_limas = ((p2*l2) * t3)/3 ;
cout<<"\n ===================================";
cout<<"\n Volume limas = "<<v_limas;
cout<<"\n ===================================";
}
return 0;
}
25. CONTOH PROGRAM MENGHITUNG LUAS PERMUKAAN DAN VOLUME KERUCUT, BOLA DAN LIMAS
#include <iostream>using namespace std;
int main()
{
float p1, p2, l1, l2, t1, t2, t3, r1, r2;
float v, lp,v_kerucut, v_bola, v_limas;
float phi=3.14159;
//p1 = panjang balok, p2= panjang alas limas
//t1=tinggi balok, t2 tinggi kerucut, t3 = tinggi limas
//r1=jari jari kerucut, r2=jari-jari bola
//proses input p,l,t
cout<<"\n ===================================";
cout<<"\n Masukkan nilai panjang balok = ";
cin>>p1;
cout<<"\n Masukkan nilai lebar balok = ";
cin>>l1;
cout<<"\n Masukkan nilai tinggi balok = ";
cin>>t1;
cout<<"\n ===================================";
cout<<"\n Masukkan nilai jari-jari kerucut = ";
cin>>r1;
cout<<"\n Masukkan nilai tinggi kerucut = ";
cin>>t2;
cout<<"\n ===================================";
cout<<"\n Masukkan nilai jari-jari bola = ";
cin>>r2;
cout<<"\n ===================================";
cout<<"\n Masukkan nilai panjang alas limas = ";
cin>>p2;
cout<<"\n Masukkan nilai lebar alas limas = ";
cin>>l2;
cout<<"\n Masukkan nilai tinggi limas = ";
cin>>t3;
//proses perhitungan
//Balok p1 l t1 v lp
v=p1*l1*t1;
lp=(2*p1*l1)+(2*p1*t1)+(2*l1*t1);
//kerucut r1, t2 v_kerucut
v_kerucut = ( phi * r1 * r1 * t2 )/3 ;
//bola r2, v_bola
v_bola = (4 * phi * r2 * r2 * r2 )/3 ;
//limas p2, l2, t3, v_limas
v_limas = ((p2*l2) * t3)/3 ;
//proses output
cout<<"\n ===================================";
cout<<"\n Volume balok = "<<v;
cout<<"\n Luas permukaan balok = "<<lp;
cout<<"\n ===================================";
cout<<"\n Volume kerucut = "<<v_kerucut;
cout<<"\n ===================================";
cout<<"\n Volume bola = "<<v_bola;
cout<<"\n ===================================";
cout<<"\n Volume limas = "<<v_limas;
cout<<"\n ===================================";
return 0;
}
26. CONTOH PROGRAM MEMBENTUK SEGITIGA LANCIP BAWAH
#include <iostream>using namespace std;
int main () {
int a,b,c;
a=4;
for (b=1;b<=a;b++){
for (c=b; c<=a;c++) {
cout << "*";
}
cout<< endl;
}
return 0;
}
27. CONTOH PROGRAM MEMBENTUK SEGITIGA LANCIP ATAS
#include <iostream>using namespace std;
int main () {
int a,b,c;
a=4;
for (b=1;b<=a;b++){
for (c=1; c<=b;c++) {
cout << "*";
}
cout<< endl;
}
return 0;
}
28. CONTOH PROGRAM LIMIT KECEPATAN INTERNET DENGAN REKURSIF
//fungsirekursif#include <iostream>
using namespace std;
int rekursif(float bandwidth, int bulan){
bandwidth = bandwidth * 1.04;
if(bulan<48){
bulan = bulan + 1;
rekursif(bandwidth,bulan);
}
else{
cout << "jumlah peningkatan bandwidth dalam 4 tahun(peningkatan 4%) adalah: " << bandwidth;
}
return 0;
}
int main(){
float awal=100;
cout << "Bandwidth awal:" << awal << endl;
rekursif(awal, 1); //bulan start from 1
return 0;
}
29. CONTOH PROGRAM MENGHITUNG BEBERAPA NILAI MATA PELAJARAN
#include<iostream>using namespace std;
//DEKLARASI STRUCK DAN VARIABEL GLOBAL===========================================================
struct grup{
int nilai;
string soal, jawaban;
};
grup pumum[4];
grup matematika[4];
grup bahasaing[4];
//FUNGSI CEK JAWABAN=============================================================================
int jawabanpumum(string ans, int x){
if(ans==pumum[x].jawaban){
return 25;
}
else{
return 0;
}
}
int jawabaninggris(string ans, int x){
if(ans==bahasaing[x].jawaban){
return 25;
}
else{
return 0;
}
}
int jawabanmtk(string ans, int x){
if(ans==matematika[x].jawaban){
return 25;
}
else{
return 0;
}
}
//FUNGSI MENGHITUNG TOTAL NILAI==================================================================
int totalnilai(int y){
int total=0;
//nilai bahasa
if(y==1){
for(int x=0;x<4;x++){
total=total+pumum[x].nilai;
}
return total;
}
//nilai matematika
else if(y==2){
for(int x=0;x<4;x++){
total=total+matematika[x].nilai;
}
return total;
}
//nilai bahasa inggris
else if(y==3){
for(int x=0;x<4;x++){
total=total+bahasaing[x].nilai;
}
return total;
}
}
//FUNGSI DATABASE==================================================================================
void DATABASE(){
//DATABASE SOAL
//BAHASA
pumum[0].soal = {"1) Kerajaan hindu tertua di Indonesia adalah kerajaan ? a)Majapahit b)Mataram lama c)Singosari d)Kutai"};
pumum[1].soal = {"2) Apakah kepanjangan PBB? a)Perkumpulan Bapak Bapak b)Persatuan Bangsa Bangsa c)Perkumpulan Bangsa Bangsa d)Perserikatan Bangsa Bangsa"};
pumum[2].soal = {"3) Perubahan benda padat menjadi gas disebut? a)Mencair b)Menyublim c)Membeku d)Meleleh"};
pumum[3].soal = {"4) Jenis makanan berikut yang tidak termasuk kabohidrat adalah? a)Nasi b)Jagung c)Telur d)Ketan"};
//MATEMATIKA
matematika[0].soal = {"1) 356 x 36 : 4 = a)3.204 b)3.402 c)3.304 d)4.204"};
matematika[1].soal = {"2) Suhu di pegunungan pada malam hari -15 0C. Pada siang hari naik 30 0C. Pada sore hari turun 18 0C. Suhu di pegunungan pada sore hari adalah ….0C. a)4 b)3 c)-3 d)-4"};
matematika[2].soal = {"3) Bu Rani membeli pakaian anak-anak seharga Rp. 65.000,00. Bila ia mendapat potongan harga 15%, Maka Bu Rani harus membayar sebesar …. a)Rp. 57.250,00 b)Rp.55.250,00 c)Rp. 56.250,00 d)Rp. 54.250,00"};
matematika[3].soal = {"4) Faktor Persekutuan Besar (FPB) dari 64, 80, dan 96 adalah …. a) 8 b) 16 c) 15 d) 30"};
//BING
bahasaing[0].soal = {"1) Do you work...the evening? a)in b)at c)on d)or"};
bahasaing[1].soal = {"2) Mr. And Mrs. Anandra... that house in 1987 a)has bought b)have bought c)bought d)buy"};
bahasaing[2].soal = {"3) I ...any parties since I lived in this town a)attend b)attended c)has attended d)have attended"};
bahasaing[3].soal = {"4) My birthday party will be celebrated .... Sunday .. 07.30 p.m. a)in – at b)on – at c)in – on d)on – in"};
//DATABASE JAWABAN
//BAHASA
pumum[0].jawaban = {"d"};
pumum[1].jawaban = {"d"};
pumum[2].jawaban = {"b"};
pumum[3].jawaban = {"c"};
//MATEMATIKA
matematika[0].jawaban = {"a"};
matematika[1].jawaban = {"c"};
matematika[2].jawaban = {"b"};
matematika[3].jawaban = {"b"};
//BAHASA INGGRIS
bahasaing[0].jawaban = {"a"};
bahasaing[1].jawaban = {"b"};
bahasaing[2].jawaban = {"d"};
bahasaing[3].jawaban = {"b"};
}
//============================================================================================
int main(){
DATABASE(); //pemanggilan DATABASE
int x;
string jwb, akhir, soallain;
int pilih, nilaiakhir=0;
do{
//pilih soal
cout << "<=================== MENU ======================>" << endl;
cout << "1) SOAL PENGETAHUAN UMUM" << endl;
cout << "2) SOAL MATEMATIKA" << endl;
cout << "3) SOAL BAHASA INGGRIS" << endl;
cout << "4) EXIT ( keluar dari program )" << endl;
cout << "PILIHAN ANDA: ";
cin >> pilih;
cout << "<===============================================>" << endl;
if(pilih==1){
//loop menampilkan array soal dan menjawab
for(x=0;x<4;x++){
cout << pumum[x].soal << endl;
cout << "JAWABAN: ";
cin >> jwb;
pumum[x].nilai=jawabanpumum(jwb, x); //memanggil fungsi mengecek jawaban
cout << endl;
}
//memamnggil fungsi menghitung nilai akhir
nilaiakhir=totalnilai(1); //1 sebagai parameter nilai bahasa
cout << "NILAI ANDA: " << nilaiakhir << endl;
}
else if(pilih==2){
//loop menampilkan array soal dan menjawab
for(x=0;x<4;x++){
cout << matematika[x].soal << endl;
cout << "JAWABAN: ";
cin >> jwb;
matematika[x].nilai=jawabanmtk(jwb, x);
cout << endl;
}
//memamnggil fungsi menghitung nilai akhir
nilaiakhir=totalnilai(2); //2 sebagai parameter nilai matematika
cout << "NILAI ANDA: " << nilaiakhir << endl;
}
else if(pilih==3){
//loop menampilkan array soal dan menjawab
for(x=0;x<4;x++){
cout << bahasaing[x].soal << endl;
cout << "JAWABAN: ";
cin >> jwb;
bahasaing[x].nilai=jawabaninggris(jwb, x);
cout << endl;
}
//memamnggil fungsi menghitung nilai akhir
nilaiakhir=totalnilai(3); //3 sebagai parameter nilai bahasa inggris
cout << "NILAI ANDA: " << nilaiakhir << endl;
}
else if(pilih==4){
break; //keluar dari loop do while
}
}while(true);
cout << "TERIMA KASIH GAES SUDAH MAU DI REPOTKAN <3<3<3";
return 0;
}
/*
PROTOTYPE PROGRAM SOAL DAN INPUT JAWABAN DENGAN KRITERIA:
1) TERDAPAT FUNGSI MODULER
a.cek jawaban
b.menghitung total nilai
c.database
2) ARRAY dan Struck
ARRAY DI DEKLARASIKAN SEBAGAI VARIABEL GLOBAL!!
a.pengetahuan umum
b.matematika
c.bahasaing
3) Menggunakan loop do-while
program dapat mengeluarkan soal lain setelah
salah satu soal selesai dikerjakan
30. CONTOH PROGRAM MENGGUNAKAN IF - ELSE
#include <iostream>using namespace std;
int main()
{
int a=100;
if (a<20)
{
cout<<"a kurang dari 20;"<<endl;
}
else
{
cout<<"a tidak kuang dari 20;"<<endl;
}
cout<<"value of a is : "<<a<<endl;
return 0;
}
31. CONTOH PROGRAM MENGGUNAKAN IF
#include <iostream>using namespace std;
int main() {
int number;
cout<<"Enter an integer: ";
cin>>number;
if(number>0) {
cout<<"you entered a positive interger: "<<number<<endl;
}
}
32. CONTOH PROGRAM MENGGUNAKAN IF BERSARANG (NESTED IF)
#include <iostream>int main() {
std::cout<<"Enter a number: ";
int x;
std::cin>>x;
if(x>10)
if(x>20) //inner if statement
std::cout<<x<<" is between 10 and 20 \n";
else
std::cout<<x<<"is greater than 20 \n";
return 0;
}
33. CONTOH PROGRAM MENGGUNAKAN IF - ELSE
#include <iostream>using namespace std;
int main() {
int a = 100;
if (a==10)
{
cout<<"Value of a is 10"<<endl;
}
else if(a==20)
{
cout<<"Value of a is 20"<<endl;
}
else if(a==30)
{
cout<<"Value of a is 30"<<endl;
}
else
{
cout<<"nilai tidak sesuai"<<endl;
}
cout<< "Exact value of a is : "<<a<<endl;
return 0;
}
34. CONTOH PROGRAM MENGGUNAKAN SWITCH - CASE
#include <iostream>using namespace std;
int main() {
//local variable declaration;
char grade = 'D';
switch (grade)
{
case 'A':
cout<<"Excellent!"<<endl;
break;
case 'B':
case 'C':
cout<<"Well Done"<<endl;
break;
case 'D':
cout<<"You passed"<<endl;
break;
case 'F':
cout<<"Better try again"<<endl;
break;
default:
cout<<"Invalid grade"<<endl;
}
cout<<"Invalid grade is "<<grade<<endl;
return 0;
}
35. CONTOH PROGRAM MENGHITUNG GAJI KARYAWAN
#include <iostream>using namespace std;
int main() {
float hours, rate, pay;
cout<<"Masukkan Jumlah Hours : ";
cin>>hours;
cout<<"Masukkan Jumlah Rate : ";
cin>>rate;
cout<< '\n';
pay=40*rate + (hours-40)*1.5*rate;
cout<<"==================================== \n";
cout<<"Jumlah Pay : " <<pay <<'\n';
return 0;
}
36. CONTOH PROGRAM MENENTUKAN BILANGAN POSITIF ATAU NEGATIF
#include <iostream>using namespace std;
int main() {
int bil;
cout<<"Masukkan Jumlah Bilangan : ";
cin>>bil;
cout<<'\n';
cout<<" \n================================"<<endl;
if (bil>=0)
{
cout<<"Bilangan Positif";
}
else
cout<<"Bilangan Negatif";
return 0;
}
37. CONTOH PROGRAM MENENTUKAN BILANGAN TERBESAR DARI 3 BILANGAN
#include <iostream>using namespace std;
int main() {
float a,b,c;
cout<<"Masukkan nilai bilangan A : ";
cin>>a;
cout<<"Masukkan nilai bilangan B : ";
cin>>b;
cout<<"Masukkan nilai bilangan C : ";
cin>>c;
cout<<"\n================================="<<endl;
if (a>b && a>c)
{
cout<<"Bilangan Terbesar adalah A = "<<a;
}
else if(b>a && b>c)
{
cout<<"Bilangan Terbesar adalah B = "<<b;
}
else
{
cout<<"Bilangan Terbesar adalah C = "<<c;
}
}
38. CONTOH PROGRAM MENGHITUNG BIAYA PENGGUNAAN AIR PDAM
PDAM menerapkan pembayaran air minum perumahan dengan cara perhitungan sebagai berikut :- Tarif per m3 untuk 10 m3 pertama (1-10) adalah 2.000
- Tarif per m3 untuk 10 m3 kedua (11-20) adalah 3.000
- Tarif per m3 untuk 10 m3 ketiga (21-30) adalah 4.000
- Tarif per m3 untuk 10 m3 selanjutnya (31 ke atas) adalah 5.000
- Pemakaian air dihitung minimal 10 m3 (kurang dari 10 m3 dianggap 10 m3)
- Biaya administrasi bulanan sebesar 10.000
Bagaimana membuat algoritma untuk menghitung biaya tersebut?
Contoh kasus
Penggunaan air 5 m3 dengan biaya 10 x 2.000 + 10.000 = 30.000
Penggunaan air 15 m3 dengan biaya 10 x 2.000 + 5 x 3.000 + 10.000 = 45.000Penggunaan air 75 m3 dengan biaya 10 x 2.000 + 10 x 3.000 + 10 x 4.000 + 45 x
5.000 +10.000 = 325.000
Buatlah flowchartnya kemudian source code
Solusi :
Pemakaian air dibagi menjadi 4 area pemakaian (misal area a,b,c,d), baru dihitung total biaya
#include <iostream>
using namespace std;
int main()
{
int a,b,c,d,pakai,biaya;
cout<<"PEMBAYARAN PEMAKAIAN AIR PDAM"<<endl;
cout<<"=========================================== \n"<<'\n';
cout<<"Masukkan Jumlah Pemakaian Air = ";
cin>>pakai;
a=10;
b=0;
c=0;
d=0;
if (pakai>30)
{
b=10; c=10; d=pakai-30;
}
else if (pakai>20)
{
b=10; c=pakai-20;
}
else if (pakai>10)
{
b=pakai-10;
}
biaya= ((a*2000)+(b*3000)+(c*4000)+(d*5000)+10000);
cout<<'\n'<<'\n';
cout<<"==========================================="<<endl;
cout<<"Total Biaya Pemakaian Air = "<<biaya<<endl;
return 0;
}
39. CONTOH PROGRAM PENGGUNAAN WHILE
#include <iostream>using namespace std;
int main() {
while(true)
{
cout<<"ini contoh bentuk while"<<endl;
}
}
40. CONTOH PROGRAM PENGGUNAAN WHILE DENGAN PEMBATASAN KONDISI
#include <iostream>using namespace std;
int main(){
int x=10;
while(x<20) // the condition is "x<10"
{
++x; //statement executed in loop
cout<<"Now x is = "<<x<<endl;
}
}
41. CONTOH PROGRAM MENGGUNAKAN WHILE DAN BREAK
#include <iostream>using namespace std;
int main() {
int i=1;
while(true)
{
cout<<"I am inside loop"<<endl;
if(i==1)
{
break;
}
}
}
42. CONTOH PROGRAM MENGHITUNG NILAI FAKTORIAL DENGAN WHILE
#include <iostream>using namespace std;
int main() {
int number,i=1, factorial=1;
cout<<"Enter ta positive interger : ";
cin>>number;
while (i<=number) {
factorial *= i; //factorial = factorial * i;
++i;
}
cout<<"Factorial of "<<number<<" = " <<factorial;
return 0;
}
43. CONTOH PROGRAM MENGGUNAKAN DO-WHILE UNTUK MENJUMLAH ANGKA
#include <iostream>using namespace std;
int main() {
float number, sum = 0.0;
do {
cout << "Enter a number : ";
cin>>number;
sum += number;
}
while (number != 0.0);
cout<< "Total sum = "<<sum;
return 0;
}
44. CONTOH PROGRAM MENGGUNAKAN FOR DALAM KASUS LIFT
#include <iostream>using namespace std;
int main() {
for (int n=10; n>0; n--) {
cout << n <<" , ";
}
cout<<"liftoff!/n";
}
45. CONTOH PROGRAM MENGHITUNG NILAI FAKTORIAL DENGAN FOR
#include <iostream>using namespace std;
int main() {
int i, n, factorial = 1;
cout<<"Enter a positive integer : ";
cin>>n;
for (i=1;i<=n;++i) {
factorial *=i; //factorial = factorial * i
}
cout<<"Factorial Of "<<n<<" = "<<factorial;
return 0;
}
46. CONTOH PROGRAM MENGGUNAKAN FOR SEDERHANA
#include <iostream>using namespace std;
int main() {
for (int i=0; i<5; i++)
cout<< " i is " << i <<endl;
return 0;
}
47. CONTOH PROGRAM PENGGUNAAK FOR DAN BREAK
#include <iostream>using namespace std;
int main() {
for ( int n=10; n>0; n--)
{
cout<<n<<" , ";
if(n==3)
{
cout<<"countdown aborted!";
break;
}
}
}
48. CONTOH PROGRAM PENGGUNAAN FOR DAN CONTINUE
#include <iostream>using namespace std;
int main() {
for(int n=10;n>0;n--){
if(n==5) continue;
cout<<n<<", ";
}
cout<<"liftoff!\n";
}
49. CONTOH PROGRAM PENGGUNAAN GO - TO
#include <iostream>using namespace std;
int main() {
int n=10;
mylabel:
cout<<n<<", ";
n--;
if(n>0) goto mylabel;
cout<<"Liftoff! \n";
}
50. CONTOH PROGRAM PENGGUNAAN WHILE DIDALAM WHILE
#include <iostream>using namespace std;
int main() {
int i = 0;
while (i<3)
{
int j =0;
while (j<5)
{
cout << " i = "<<i<<" and j = "<<j<<endl;
j++;
}
i++;
}
return 0;
}
51. CONTOH PROGRAM NESTED LOOP MENGGUNAKAN DO - WHILE
#include <iostream>using namespace std;
int main() {
int i = 0;
do
{
int j=0;
do
{
cout<<" i = "<<i<<" and j = "<<j<<endl;
j++;
}while (j<5);
i++;
}while(i<3);
return 0;
}
52. CONTOH PROGRAM NESTED LOOP MENGGUNAKAN FOR
#include<iostream>using namespace std;
int main() {
for (int i=0; i<3; i++)
{
int j=0;
for (int j=0; j<5; j++)
{
cout << "i = "<<i<<" and j "<<j<<endl;
}
}
return 0;
}
53. CONTOH PROGRAM MENGHITUNG RATA-RATA 3 BILANGAN DENGAN WHILE
#include <iostream>using namespace std;
int main() {
float jumlah, x, rerata;
int bilangan;
jumlah=0;
bilangan=3;
cout<<"#*PROGRAM RATA-RATA 3 BILANGAN*# \n";
do {
cout<<"Masukkan bilangan : ";
cin>>x;
jumlah = jumlah + x;
bilangan--;
} while (bilangan>0);
rerata = jumlah / 3;
cout<<"Reratanya adalah : "<<rerata;
}
54. CONTOH PROGRAM MENAMPILKAN KARAKTER DENGAN WHILE
#include <iostream>using namespace std;
int main() {
int i;
i=0;
do {
cout<<" * ";
i++;
}while (i<5);
return 0;
}
55. CONTOH PROGRAM INPUT SEDERHANA DENGAN WHILE
#include <iostream>using namespace std;
int main() {
int i, nilai;
i=1;
while (i<=3)
{
cout<<"Nilai Mahasiswa ke - "<<i<<" adalah : ";
cin>>nilai;
i++;
}
return 0;
}
56. CONTOH PROGRAM TEBAK-TEBAKAN SEDERHANA DENGAN WHILE
#include <iostream>using namespace std;
int main() {
char huruf;
cout<<"Masukkan Tebakan Anda : ";
cin>>huruf;
while(huruf!='q') {
cout<<"Maaf Anda Salah \n";
cout<<"Masukkan Tebakan Anda : ";
cin>>huruf;
}
cout<<"Anda benar!!!!!";
return 0;
}
57. CONTOH PROGRAM PENGGUNAAN FOR DAN SHORTHAND SSIGNMENT OPERATOR
#include <iostream>using namespace std;
int foo[] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for (n=0; n<5; ++n)
{
result += foo[n];
}
cout << result;
return 0;
}
58. CONTOH PROGRAM MENAMPILKAN ISI ARRAY
#include <iostream>using namespace std;
void printarray (int arg[], int length) {
for (int n=0 ; n<length; ++n)
cout<<arg[n]<<' ';
cout<< '\n';
}
int main()
{
int firstarray[]={5, 10, 15};
int secondarray[]={2, 4, 6, 8, 10};
printarray (firstarray, 3);
printarray (secondarray,5);
}
59. CONTOH PROGRAM MENJUMLAH DATA DALAM ARRAY
#include <iostream>using namespace std;
int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 Numbers : ";
//storing 5 number entered by user in array
//finding the sum of number entered
for (int i = 0; i<5; ++i)
{
cin>>numbers[i];
sum+=numbers[i];
}
cout<<" SUM = "<<sum<<endl;
return 0;
}
60. CONTOH PROGRAM ARRAY DUA DIMENSI
#include <iostream>using namespace std;
int main()
{
int x;
int y;
int array[8][8]; // declares an array like a chessboard
for(x=0; x<8; x++) {
for (y=0; y<8; y++)
array[x][y]=x*y; // set each elament to a value
}
cout<<"Array Indices : \n";
for (x=0; x<8; x++) {
for(y=0; y<8; y++)
cout<<"["<<x<<"]["<<y<<"]"<<array [x][y]<<" ";
cout<<"\n";
}
cin.get();
}
61. CONTOH PROGRAM ARRAY SEDERHANA
#include <iostream>int main()
{
short age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
std::cout<<age[0]<<std::endl;
std::cout<<age[1]<<std::endl;
std::cout<<age[2]<<std::endl;
std::cout<<age[3]<<std::endl;
return 0;
}
62. CONTOH PROGRAM MENGAMBIL NILAI DARI ARRAY LAIN
#include <iostream>int main()
{
short age[4];
short same_age[4];
age[0] = 23;
age[1] = 34;
age[2] = 65;
age[3] = 74;
same_age[0] = age[0];
same_age[1] = age[1];
same_age[2] = age[2];
same_age[3] = age[3];
std::cout<<same_age[0]<<std::endl;
std::cout<<same_age[1]<<std::endl;
std::cout<<same_age[2]<<std::endl;
std::cout<<same_age[3]<<std::endl;
return 0;
}
63. CONTOH PROGRAM ARRAY DUA DIMENSI SEDERHANA
#include <iostream>using namespace std;
int main()
{
int test[3][2] =
{
{2, -5},
{4, 0},
{9, 1}
} ;
for (int i = 0; i<3; ++i)
{
for(int j = 0; j<2; ++j)
{
cout << "test ["<<i<<"] ["<<j<<"]"<<test[i][j]<<endl;
}
}
return 0;
}
64. CONTOH PROGRAM ARRAY DENGAN KONSTANTA
#include <iostream>using namespace std;
const int CITY=2;
const int WEEK=7;
int main()
{
//inserting the values into the temperature array
int temperature [CITY][WEEK];
cout<< "Enter all temperature for a week of first city and then second city. \n";
for (int i=0; i < CITY; ++i)
{
for (int j = 0; j<WEEK; ++j)
{
cout<<"City "<<i+1<<", Day"<<j+1<<" : ";
cin>>temperature[i][j];
}
}
cout<<"\n \n Displaying Values : \n";
//accessing the values from the temperature array
for(int i = 0; i<CITY; ++i)
{
for(int j = 0; j<WEEK; ++j)
{
cout<<"City"<<i+1<<", Day"<<j+1<<" = "<<temperature[i][j]<<endl;
}
}
return 0;
}
65. CONTOH PROGRAM ARRAY 3 DIMENSI
#include <iostream>using namespace std;
int main()
{
//this array can store up to 12 elements (2x3x2)
int test[2][3][2];
cout<<"Enter 12 Values: \n";
//inserting the values into the test array
//using 3 nested fo loops.
for(int i=0; i<2;++i)
{
for(int j=0; j<3;++j)
{
for(int k=0; k<2;++k)
{
cin>>test[i][j][k];
}
}
}
//displaying the values with proper index.
for(int i=0; i<2;++i)
{
for(int j=0; j<3;++j)
{
for(int k=0; k<2;++k)
{
cout<<"test ["<<i<<"]["<<j<<"]["<<k<<"] = "<<test[i][j][k]<<endl;
}
}
return 0;
}
}
66. CONTOH PROGRAM PENGGUNAAN STRUCT DAN ARRAY
#include <iostream>using namespace std;
int main()
{
//deklarasi struct dengan nama mahasiswa
struct mahasiswa
{
//isi dari tipe data bentukan mahasiswa
int nim;
char nama[20];
char gender[10];
};
//inisialisasi mhs ke tipe data mahasiswa dengan arraynya
mahasiswa mhs[2];
//perulangan untuk menginputkan
for (int i = 0; i<2; i++)
{
cout <<"NIM : ";
cin>>mhs[i].nim;
cout <<"Nama : ";
cin>>mhs[i].nama;
cout <<"Jenis Kelamin : ";
cin>>mhs[i].gender;
}
//perulangan untuk menampilkan
for (int i=0; i<2; i++)
{
cout<<"========================== \n";
cout<<"NIM : "<<mhs[i].nim<<endl;
cout<<"Nama : "<<mhs[i].nama<<endl;
cout<<"Jenis Kelamin : "<<mhs[i].gender<<endl;
}
return 0;
}
67. CONTOH PROGRAM MENCARI BILANGAN KELIPATAN EMPAT DENGAN ARRAY
#include <iostream>using namespace std;
int main()
{
int nilai[10];
for (int p=0; p<10; p++)
{
nilai[p] = p+2;
};
for (int p=0; p<10; p++)
{
if (p%4==0)
{
cout<<" ";
}
else
{
cout<<nilai[p];
};
}
}
68. CONTOH PROGRAM MENGHITUNG NILAI RATA-RATA MAHASISWA DENGAN ARRAY
#include <iostream>using namespace std;
int main()
{
int nilai[5], x, jumlah, rata;
for(x=0; x<5; x++)
{
cout << "Masukkan Nilai Mahasiswa "<<x<< " : ";
cin>>nilai[x];
}
for(x=0; x<5; x++)
{
jumlah= jumlah + nilai[x];
}
rata= jumlah /5;
cout<<"Nilai Rata-rata : "<<rata;
}
69. CONTOH PROGRAM MENGGUNAKAN ARRAY
#include <iostream>using namespace std;
int main()
{
int i, j, x, n;
int array[x];
cin>>n;
for (i=0 ; i<=n; i++ )
{
for (j=0; j<=n; j++ )
{
x=j;
if (x<=i)
{
x=j+1;
array[x];
}
else
{
x=0;
array[x];
};
}
}
for (i=1 ; i<=n; i++ )
{
for (j=1; j<=n; j++ )
{
cout<<array[x]<<"\n";
};
}
}
70. CONTOH PROGRAM PENJUMLAHAN DENGAN FUNGSI
#include <iostream>using namespace std;
int addition(int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z=addition(5,3);
cout<<"The Result is "<<z;
}
71. CONTOH PROGRAM PENGURANGAN DENGAN FUNGSI
#include <iostream>using namespace std;
int subtraction (int a, int b)
{
int r;
r=a-b;
return r;
}
int main ()
{
int x=5 , y=3 , z;
z=subtraction (7,2);
cout<<"The first result is "<<z<<'\n';
cout<<"The second result is "<<subtraction (7,2)<<'\n';
cout<<"The third result is "<<subtraction (x,y)<<'\n';
z=4+subtraction (x,y);
cout<<"The fourt result is "<<z<<'\n';
}
72. CONTOH PROGRAM MENAMPILKAN KATA DENGAN FUNGSI
#include <iostream>using namespace std;
void printmessage ()
{
cout<<"I'm a function";
}
int main()
{
printmessage ();
}
73. CONTOH PROGRAM PEMBAGIAN MENGGUNAKAN FUNGSI
#include <iostream>using namespace std;
int divide (int a, int b=2)
{
int r;
r=a/b;
return (r);
}
int main()
{
cout<<divide(12)<<'\n';
cout<<divide(20,4)<<'\n';
return 0;
}
74. CONTOH PROGRAM MENCARI DUA BILANGAN TERBESAR DENGAN FUNGSI MAX
#include <iostream>using namespace std;
//function declaration
int max (int num1, int num2);
int main()
{
//local variabel declaration
int a=100;
int b=200;
int ret;
//calling a function to get max value.
ret=max(a,b);
cout<<"Max value is : "<<ret<<endl;
return 0;
}
//function returning the max between two numbers
int max(int num1, int num2) {
//local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result=num2;
return result;
}
75. CONTOH PROGRAM PENJUMLAHAN DENGAN FUNGSI
#include <iostream>using namespace std;
int sum ( int a, int b=20)
{
int result;
result =a+b;
return (result);
}
int main ()
{
//local variable declaration:
int a = 100;
int b = 200;
int result;
//calling a function to add the values.
result=sum(a,b);
cout<<"Total value is : "<<result<<endl;
//calling a function again as follows.
result=sum(a);
cout<<"Total value is : "<<result<<endl;
return 0;
}
76. CONTOH PROGRAM PENJUMLAHAN DENGAN FUNGSI ADD
#include <iostream>using namespace std;
//function prototype (declaration)
int add(int, int);
int main ()
{
int num1, num2, sum;
cout<<"Enter two numbers to add : \n";
cin>>num1>>num2;
//function call
sum = add (num1, num2);
cout<<"Sum = "<<sum;
return 0;
}
//function definition
int add (int a, int b)
{
int add;
add=a+b;
//return statement
return add;
}
77. CONTOH PROGRAM MENGECEK BILANGAN POSITIVE DENGAN FUNGSI
#include <iostream>using namespace std;
//function
bool checkifpositive(int x)
{
if (x>=0)
return true;
return false;
}
//procedure
void printifpositive (int x)
{
bool ispositive = checkifpositive(x);
if(ispositive)
cout<<"X is positive and its value is " << x << endl;
}
int main()
{
printifpositive(3);
printifpositive(-54);
printifpositive(710);
return 0;
}
78. CONTOH PROGRAM MENETUKAN BILANGAN GENAP DAN GANJIL DENGAN FUNGSI
#include <iostream>using namespace std;
void odd(int x);
void even(int x);
int main()
{
int i;
do {
cout<<"Please enter number (0 to exit) : ";
cin>>i;
odd(i);
return 0;
} while (i!=0);
return 0;
}
void odd(int x)
{
if ((x%2)!=0) cout <<"It is odd. /n";
else even (x);
}
void even (int x)
{
if((x%2)==0) cout<<"it is even. /n";
else odd (x);
}
79. CONTOH PROGRAM MENGHITUNG NILAI FAKTORIAL DENGAN FUNGSI
#include <iostream>using namespace std;
long factorial (long a)
{
if (a>1)
return (a*factorial (a-1));
else
return 1;
}
int main()
{
long number =9;
cout<<number <<" ! = "<<factorial (number);
return 0;
}
80. CONTOH PROGRAM MENGHITUNG JUMLAH DIANTARA 2 BILANGAN
#include <iostream>using namespace std;
int logika (int a, int b)
{
int i, sum=0, sum1=0, sum2=0;
if(a<b){
for (i=a; i<=b; i++){
sum=sum+i;
}
return sum;
}
else if(a>b){
for(i=a; i>=b; i--){
sum1=sum1+i;
}
return sum1;
}
else if (a==b){
sum2=a;
return sum2;
}
}
//int kurang (int a, int b)
int main()
{
int first, last, total;
cout<<"Masukkan nilai awal dan nilai akhir : \n";
cin>>first>>last;
total=logika(first, last);
cout<<"Jumlah dari semua nila pada rentan bilangan awal dan akhir : ";
cout<<total;
return 0;
}
81. CONTOH PROGRAM MENGECEK KE VALID DATA
#include <iostream>using namespace std;
bool valid(int x){
if(x>=15){
return true;
}
else{
return false;
}
}
void syarat (int x){
bool finalpositive;
finalpositive=valid(x);
if(finalpositive){
cout<<'\n'<<"===========================================================\n";
cout<<"Silahkan Masuk!";
}
else{
cout<<'\n'<<"===========================================================\n";
cout<<"DILARANG MASUK!";
}
}
int main(){
int umur, umurortu, selisih;
string namaanak, namaortu;
cout<<"Masukkan Nama Kamu dan Nama Orang Tuamu : \n";
cin>>namaanak>>namaortu;
cout<<"Masukkan Umur Kamu dan Umur Orang Tuamu : \n";
cin>>umur>>umurortu;
selisih = umurortu-umur;
syarat(selisih);
return 0;
}
82. CONTOH PROGRAM POINTER SEDERHANA
#include <iostream>
using namespace std;
int main()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout<<"Firstvalue is "<<firstvalue<<'\n';
cout<<"Secondvalue is "<<secondvalue<<'\n';
return 0;
}
83. CONTOH PROGRAM POINTER SEDERHANA 2
#include <iostream>
using namespace std;
int main()
{
int firstvalue=5, secondvalue=15;
int *p1, *p2;
p1 = &firstvalue; //p1 = address of firstvalue
p2 = &secondvalue; //p2 = address of secondvalue
*p1 = 10; //value pointed to by p1 = 10
*p2 = *p1; //value pointed to by p2 = value pointed to by p1
p1 = p2; //p1=p2 (value of pointer is copied)
*p1=20; // value pointed to by p1 = 20
cout << " Firstvalue is "<<firstvalue<<'\n';
cout<<" Secondvalue is "<<secondvalue<<'\n';
return 0;
}
84. CONTOH PROGRAM ARRAY DALAM POINTER
#include <iostream>
using namespace std;
int main()
{
int numbers [5];
int *p;
p=numbers; *p=10;
p++; *p=20;
p=&numbers[2]; *p=30;
p=numbers + 3; *p=40;
p=numbers; *(p+4)=50;
for (int n=0; n<5; n++)
cout<<numbers[n]<<", ";
return 0;
}
85. CONTOH PROGRAM PENGGUNAN POINTER DALAM FUNGSI
#include <iostream>
using namespace std;
void increment_all( int *start, int *stop)
{
int * current = start;
while (current != stop) {
++(*current); //increment value pointed;
++current; //increment pointer
}
}
void print_all (const int *start, const int *stop)
{
const int * current = start;
while (current != stop) {
cout << *current << '\n';
++current; //increment pointer
}
}
int main()
{
int numbers[]={10,20,30};
increment_all (numbers, numbers+3);
print_all (numbers, numbers+3);
return 0;
}
86. CONTOH PROGRAM PENGGUNAAN POINTER DENGAN TIPE RETURN VOID
#include <iostream>
using namespace std;
void increase (void * data, int psize)
{
if (psize == sizeof(char))
{char * pchar; pchar = (char*)data; ++(*pchar);}
else if (psize == sizeof (int))
{int * pint; pint = (int *)data; ++(*pint);}
}
int main ()
{
char a = 'x';
int b = 1602;
increase (&a, sizeof (a));
increase (&b, sizeof (b));
cout<<a<<", "<<b<<'\n';
return 0;
}
87. CONTOH PROGRAM PENGGUNAAN STRUCT
//#include "stdafx.h"
#include <iostream>
using namespace std;
int main(){
struct
{
char nim[8];
char nama[15];
float nilai;
}mahasiswa;
cout<<"Masukkan NIM: ";
cin>>mahasiswa.nim;
cout<<"Masukkan nama: ";
cin>>mahasiswa.nama;
cout<<"Masukkan nilai: ";
cin>>mahasiswa.nilai;
//tampilkan hasil
cout <<"NIM : "<<" "<<mahasiswa.nim<<endl;
cout <<"Nama : "<<" "<<mahasiswa.nama<<endl;
cout <<"Nilai : "<<" "<<mahasiswa.nilai<<endl;
return 0;
}
88. CONTOH PROGRAM PENGGUNAAN POINTER ARRAY
//#include "stdafx.h"
#include "iostream"
using namespace std;
int main(){
int nilai[5], *p;
p=nilai;
*p=10;
p++;*p=20;
p=&nilai[2]; *p=30;
p=nilai+3; *p=40;
p=nilai; *(p+4)=50;
for(int n=0; n<5; n++) {
cout<<" "<<nilai[n]<<endl;
}
return 0;
}
89. CONTOH PROGRAM MENGEDIT DATA DALAM ARRAY
//#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{int A [5] = {20,9,1986,200,13};
int n;
cout<<"Data yang lama \n";
for (n=0; n<5;n++)
{
cout<<" "<<A[n];
}cout<<"\n Data yang baru : \n";
A[0]=4;
A[1]=2;
A[2]=1;
A[3]=3;
A[4]=5;
for(n=0;n<5;n++)
{
cout<<" "<<A[n];
}
return 0;
}
90. CONTOH PROGRAM PENGGUNAAN ARRAY SEDERHANA
//#include "stdafx.h"
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::setw;
int main(){
const int MAX(20); //nilai maksimal dari variabel
double gas[ MAX ]; //jumlah gas ukuran tabung
long miles [ MAX ]; //pembacaan odometer
int count(0); //loop counter
char indicator('y'); //input indicator
while(('y'==indicator || 'Y'==indicator) && count<MAX){
cout<<endl<<"Masukkan jumlah gas: ";
cin>>gas[count]; //read odometer value
++count;
cout<<"Apakah anda akan menambah data ( y or n)? ";
cin>>indicator;}
if(count<1) // count = 1 setelah 1 data dimasukkan
{
cout<<endl<<"Sorry - data anda kurang dari 2.";
return 0;
} //output result from 2nd entry to last entry
for(int i=1; i<count; i++){
cout<<endl<<setw(2)<<i<<"."//output sequence number
<<"gas terjual = "<<gas[i]<<" gallons " //output gas
<<"menghasilkan "//output miles per gallon
<<(miles[i] - miles[i-1])/gas[i]<<" miles per gallon.";}
cout <<endl;
return 0;
}
91. CONTOH PROGRAM ARRAY MULTIDIMENSI
//#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char stars[6][80] = {"justin","Happalong Cassidy", "Jessie j", "adele", "ariana","oliver hardy"};
int d(0);
cout<<endl<<"masukkan angka antara 1 dan 6 : ";
cin>>d;
if(d>=1 && d<=6) // mengecek input antar 1-6
cout<<endl //output
<<"Bintang keberuntunganmu adalah: "<<stars[d-1];
else
cout<<endl //jika input salah
<<"Sorry, you haven't got a lucky star.";
cout<<endl;
return 0;
}
92. CONTOH PROGRAM ARRAY SATU DIMENSI
//#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int y[100];
int i, k;
for(i=0;i<10;i++){
k=i+1;
y[i]=k*k;
cout<<"pangkat dari "<<" "<<k<<"adalah"<<" "<<y[i]<<endl;
}
return 0;
}
93. CONTOH PROGRAM ARRAY DUA DIMENSI
//#include "stdafx.h"
#include <iostream>
using namespace std;
void cetakarray(int [][3]);
int main(){
int matrik1[2][3]={
{1,2,3},{4,5,6}},
matrik2[2][3]= {1,2,3,4,5},
matrik3[2][3]= { {1,2}, {4}
};
cetakarray(matrik1);
cetakarray(matrik2);
cetakarray(matrik3);
return 0;}
void cetakarray(int a[][3]){
int i,j;
for (i=0; i<=1;i++){
for(j=0;j<=2;j++)
cout<<" "<<a[i][j];
cout<<"\n";}}
94. CONTOH PROGRAM DESCENDING LINKED LIST
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef struct item{
int val;
item *next;
}item;
int main(){
item*head=NULL;
int t;
for(i=0;i<=30;i++){
item *curr = new item;
curr-> val=i;
curr->next=head;
head=curr;
}
while(head){
cout<<head->val<<" ";
head=head->next;
}
return 0;
}
95. CONTOH PROGRAM LINKED LIST
#include <iostream>
#include<conio.h>
#include<windows.h>
#include <stdio.h>
using namespace std;
int pil;
void pilih();
void buat_baru();
void tambah_belakang();
void tambah_depan();
void hapus_belakang();
void hapus_depan();
void tampil();
struct simpul{
char nim[8], nama[80];
int umur;
struct simpul *next;
}mhs, *baru, *awal=NULL, *akhir=NULL, *hapus, *bantu;
void clrscr(){
system("cls");
}
int main(){
do{
clrscr();
cout << "MENU SINGLE LINKEDLIST" << endl;
cout << "1. Tambah Depan" << endl;
cout << "2. Tambah Belakang" << endl;
cout << "3. Hapus Depan" << endl;
cout << "4. Hapus Belakang" << endl;
cout << "5. Tampil" << endl;
cout << "6. Selesai" << endl;
cout << "Pilihan anda: ";
cin>>pil;
pilih();
}while (pil!=6);
return 0;
}
void pilih(){
if(pil==1){
tambah_depan();
}
else if(pil==2){
tambah_belakang();
}
else if(pil==3){
hapus_depan();
}
else if(pil==4){
hapus_belakang();
}
else if(pil==5){
tampil();
}
}
void buat_baru(){
baru=(simpul*)malloc(sizeof(struct simpul));
cout << "Input NIM : ";
cin >> baru->nim;
cout << "Input Nama : ";
cin >>baru->nama;
cout << "Input Umur : ";
cin >> baru->umur;
baru->next=NULL;
}
void tambah_belakang(){
buat_baru();
if(awal==NULL){
awal=baru;
}
else{
akhir->next=baru;
}
akhir=baru;
akhir->next=NULL;
cout << endl << endl;
tampil();
}
void tambah_depan(){
buat_baru();
if(awal==NULL){
awal=baru;
akhir=baru;
akhir->next=NULL;
}
else{
baru->next=awal;
awal=baru;
}
cout << endl << endl;
tampil();
}
void hapus_depan(){
if(awal==NULL){
cout<<"kosong";
}
else{
hapus = awal;
awal=awal->next;
free(hapus);
}
cout << endl << endl;
tampil();
}
void hapus_belakang(){
if(awal==NULL){
cout << "Kosong";
}
else if(awal==akhir){
hapus = awal;
awal=awal->next;
free(hapus);
}
else{
hapus = awal;
while(hapus->next != akhir){
hapus = hapus->next;
akhir=hapus;
hapus=akhir->next;
akhir->next=NULL;
free(hapus);
}
}
cout << endl << endl;
tampil();
}
void tampil(){
if(awal==NULL){
cout << "Kosong";
}
else{
bantu=awal;
while(bantu!=NULL){
cout << "NIM : " << bantu->nim << endl;
cout << "NAMA : " << bantu->nama << endl;
cout << "UMUR : " << bantu->umur << endl;
bantu=bantu->next;
}
}
getch();
}
96. CONTOH PROGRAM SISIP LIST
#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
typedef struct node{
int data;
struct node *next;
}NOD, *NODPTR;
void buatlist(NODPTR *s){
*s=NULL;
}
NODPTR NodBaru(int m){
NODPTR n;
n=(NODPTR) malloc(sizeof(NOD));
if(n!=NULL){
n->data=m;
n->next=NULL;
}
return n;
}
void insertlist(NODPTR*s, NODPTR t, NODPTR p){
if(p==NULL){
t->next=*s;
*s=t;
}
else{
t->next=p->next;
p->next=t;
}
}
void cetaklist(NODPTR s){
NODPTR ps;
for(ps=s;ps != NULL;ps=ps->next){
cout << " " << ps ->data<<"-->"<<endl;
}
}
int main(){
NODPTR pel;
NODPTR n;
buatlist(&pel);
n=NodBaru(55);
insertlist(&pel, n, NULL);
n=NodBaru(75);
insertlist(&pel, n, NULL);
n=NodBaru(60);
insertlist(&pel, n, NULL);
n=NodBaru(20);
insertlist(&pel, n, NULL);
n=NodBaru(33);
insertlist(&pel, n, NULL);
cetaklist(pel);
return 0;
}
97. CONTOH PROGRAM DOUBLE LINKED LIST
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct node{
int info;
struct node *next;
struct node *prev;
}*start;
class double_llist {
public:
void create_list(int value);
void add_begin(int value);
void add_after(int value, int position);
void delete_element (int value);
void searc_element(int value);
void display_dlist();
void count();
void reverse();
double_llist() {
start = NULL;
}
};
int main()
{
int choice, element, position;
double_llist dl;
while (1){
cout<<"-------------------------"<<endl;
cout<<"-------------------------"<<endl;
cout<<"1. Create Node"<<endl;
cout<<"2. Add after beginning"<<endl;
cout<<"3. Add after position"<<endl;
cout<<"4. Delete"<<endl;
cout<<"5. Display"<<endl;
cout<<"6. Count"<<endl;
cout<<"7. Reverse"<<endl;
cout<<"8. Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch (choice)
{
case 1:
cout<<"Enter the element : ";
cin>>element;
dl.create_list(element);
cout<<endl;
break;
case 2:
cout<<"Enter the element : ";
cin>>element;
dl.add_begin(element);
cout<<endl;
break;
//case 3:
// cout<<"Enter the element : ";
// cin>>element;
// dl.add_begin(element);
// cout<<endl;
// break;
case 4:
if(start == NULL)
{
cout<<"List Empty, nothing to delete"<<endl;
break;
}
cout<<"enter the element for deletion : ";
cin>>element;
dl.delete_element(element);
cout<<endl;
break;
case 5:
dl.display_dlist();
cout<<endl;
break;
case 6:
dl.count();
break;
//case 7:
case 8:
exit(1);
default:
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
void double_llist::create_list(int value)
{
struct node *s, *temp;
temp=new(struct node);
temp->info=value;
temp->next=NULL;
if (start==NULL)
{
temp->prev=NULL;
start = temp;
}
else
{
s=start;
while (s->next != NULL)
s=s->next;
temp->prev=s;
}
}
void double_llist::add_begin(int value)
{
if (start == NULL)
{
cout<<"First Create the list "<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->prev=NULL;
temp->info=value;
temp->next=start;
start->prev=temp;
start=temp;
cout<<"element inserted"<<endl;
}
void double_llist::delete_element(int value)
{
struct node *tmp, *q;
if(start->info==value)
{
tmp=start;
start=start->next;
start->prev=NULL;
cout<<"element deleted"<<endl;
}
q=start;
while (q->next->next != NULL)
{
if (q->next->info==value)
{
tmp=q->next;
q->next=tmp->next;
tmp->next->prev=q;
cout<<"element deleted"<<endl;
free(tmp);
return;
}
q=q->next;
}
if(q->next->info==value)
{
tmp=q->next;
free(tmp);
q->next=NULL;
cout<<"element deleted"<<endl;
return;
}
cout<<"element "<<value<<" not found"<<endl;
}
void double_llist::display_dlist()
{
struct node *q;
if (start == NULL)
{
cout<<"List empty, nothing to display"<<endl;
return;
}
q=start;
cout<<"the doubly link is :"<<endl;
while(q!=NULL)
{
cout<<q->info<<" <-> ";
q=q->next;
}
cout<<"NULL"<<endl;
}
void double_llist::count()
{
struct node *q = start;
int cnt = 0;
while (q != NULL)
{
q=q->next;
cnt++;
}
cout<<"Number of element are : "<<cnt<<endl;
}
98. CONTOH PROGRAM DOUBLE LINKED LIST SINGULAR
/*
* C++ Program to Implement Circular Doubly Linked List
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int info;
struct node *next;
struct node *prev;
}*start, *last;
int counter = 0;
/*
* Class Declaration
*/
class double_clist
{
public:
node *create_node(int);
void insert_begin();
void insert_last();
void insert_pos();
void delete_pos();
void search();
void update();
void display();
void reverse();
void sort();
double_clist()
{
start = NULL;
last = NULL;
}
};
/*
* Main: Contains Menu
*/
int main()
{
int choice;
double_clist cdl;
while (1)
{
cout<<"\n-------------------------------"<<endl;
cout<<"Operations on Doubly Circular linked list"<<endl;
cout<<"\n-------------------------------"<<endl;
cout<<"1.Insert at Beginning"<<endl;
cout<<"2.Insert at Last"<<endl;
cout<<"3.Insert at Position"<<endl;
cout<<"4.Delete at Position"<<endl;
cout<<"5.Update Node"<<endl;
cout<<"6.Search Element"<<endl;
cout<<"7.Sort"<<endl;
cout<<"8.Display List"<<endl;
cout<<"9.Reverse List"<<endl;
cout<<"10.Exit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cdl.insert_begin();
break;
case 2:
cdl.insert_last();
break;
case 3:
cdl.insert_pos();
break;
case 4:
cdl.delete_pos();
break;
case 5:
cdl.update();
break;
case 6:
cdl.search();
break;
case 7:
cdl.sort();
break;
case 8:
cdl.display();
break;
case 9:
cdl.reverse();
break;
case 10:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}
/*
*MEMORY ALLOCATED FOR NODE DYNAMICALLY
*/
node* double_clist::create_node(int value)
{
counter++;
struct node *temp;
temp = new(struct node);
temp->info = value;
temp->next = NULL;
temp->prev = NULL;
return temp;
}
/*
*INSERTS ELEMENT AT BEGINNING
*/
void double_clist::insert_begin()
{
int value;
cout<<endl<<"Enter the element to be inserted: ";
cin>>value;
struct node *temp;
temp = create_node(value);
if (start == last && start == NULL)
{
cout<<"Element inserted in empty list"<<endl;
start = last = temp;
start->next = last->next = NULL;
start->prev = last->prev = NULL;
}
else
{
temp->next = start;
start->prev = temp;
start = temp;
start->prev = last;
last->next = start;
cout<<"Element inserted"<<endl;
}
}
/*
*INSERTS ELEMNET AT LAST
*/
void double_clist::insert_last()
{
int value;
cout<<endl<<"Enter the element to be inserted: ";
cin>>value;
struct node *temp;
temp = create_node(value);
if (start == last && start == NULL)
{
cout<<"Element inserted in empty list"<<endl;
start = last = temp;
start->next = last->next = NULL;
start->prev = last->prev = NULL;
}
else
{
last->next = temp;
temp->prev = last;
last = temp;
start->prev = last;
last->next = start;
}
}
/*
*INSERTS ELEMENT AT POSITION
*/
void double_clist::insert_pos()
{
int value, pos, i;
cout<<endl<<"Enter the element to be inserted: ";
cin>>value;
cout<<endl<<"Enter the postion of element inserted: ";
cin>>pos;
struct node *temp, *s, *ptr;
temp = create_node(value);
if (start == last && start == NULL)
{
if (pos == 1)
{
start = last = temp;
start->next = last->next = NULL;
start->prev = last->prev = NULL;
}
else
{
cout<<"Position out of range"<<endl;
counter--;
return;
}
}
else
{
if (counter < pos)
{
cout<<"Position out of range"<<endl;
counter--;
return;
}s
= start;
for (i = 1;i <= counter;i++)
{
ptr = s;
s = s->next;
if (i == pos - 1)
{
ptr->next = temp;
temp->prev = ptr;
temp->next = s;
s->prev = temp;
cout<<"Element inserted"<<endl;
break;
}
}
}
}
/*
* Delete Node at Particular Position
*/
void double_clist::delete_pos()
{
int pos, i;
node *ptr, *s;
if (start == last && start == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
return;
}
cout<<endl<<"Enter the postion of element to be deleted: ";
cin>>pos;
if (counter < pos)
{
cout<<"Position out of range"<<endl;
return;
} s
= start;
if(pos == 1)
{
counter--;
last->next = s->next;
s->next->prev = last;
start = s->next;
free(s);
cout<<"Element Deleted"<<endl;
return;
}
for (i = 0;i < pos - 1;i++ )
{
s = s->next;
ptr = s->prev;
}
ptr->next = s->next;
s->next->prev = ptr;
if (pos == counter)
{
last = ptr;
}
counter--;
free(s);
cout<<"Element Deleted"<<endl;
}
/*
* Update value of a particular node
*/
void double_clist::update()
{
int value, i, pos;
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to update"<<endl;
return;
}
cout<<endl<<"Enter the postion of node to be updated: ";
cin>>pos;
cout<<"Enter the new value: ";
cin>>value;
struct node *s;
if (counter < pos)
{
cout<<"Position out of range"<<endl;
return;
} s
= start;
if (pos == 1)
{
s->info = value;
cout<<"Node Updated"<<endl;
return;
}
for (i=0;i < pos - 1;i++)
{
s = s->next;
} s
->info = value;
cout<<"Node Updated"<<endl;
}
/*
* Search Element in the list
*/
void double_clist::search()
{
int pos = 0, value, i;
bool flag = false;
struct node *s;
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to search"<<endl;
return;
}
cout<<endl<<"Enter the value to be searched: ";
cin>>value;
s = start;
for (i = 0;i < counter;i++)
{
pos++;
if (s->info == value)
{
cout<<"Element "<<value<<" found at position: "<<pos<<endl;
flag = true;
} s
= s->next;
}
if (!flag)
cout<<"Element not found in the list"<<endl;
}
/*
* Sorting Doubly Circular Link List
*/
void double_clist::sort()
{
struct node *temp, *s;
int value, i;
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to sort"<<endl;
return;
} s
= start;
for (i = 0;i < counter;i++)
{
temp = s->next;
while (temp != start)
{
if (s->info > temp->info)
{
value = s->info;
s->info = temp->info;
temp->info = value;
}
temp = temp->next;
} s
= s->next;
}
}
/*
* Display Elements of the List
*/
void double_clist::display()
{
int i;
struct node *s;
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to display"<<endl;
return;
}
s = start;
for (i = 0;i < counter-1;i++)
{
cout<<s->info<<"<->";
s = s->next;
}
cout<<s->info<<endl;
}
/*
* Reverse Doubly Circular Linked List
*/
void double_clist::reverse()
{
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to reverse"<<endl;
return;
}
struct node *p1, *p2;
p1 = start;
p2 = p1->next;
p1->next = NULL;
p1->prev = p2;
while (p2 != start)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
last = start;
start = p1;
cout<<"List Reversed"<<endl;
}
6. program linked list
#include <iostream>
#include <conio.h>
#include <stdio.h>
using namespace std;
//1
int pilih;
void pilihan();
void insert_data();
void delete_data();
void display_data();
struct node
{
int nim;
char nama [40];
char gender [20];
float nilai;
struct node *next;
struct node *prev;
//2
};
node *baru, *head=NULL, *tail=NULL,*help,*del;
int main()
{
do
{
cout<<endl;
cout<<"\t DOUBLY LINKED LIST"<<endl;
cout<<"\t=========================="<<endl;
cout<<"\t1. INSERT DATA"<<endl;
cout<<"\t2. HAPUS DATA"<<endl;
cout<<"\t3. CETAK DATA"<<endl;
cout<<"\t4. EXIT"<<endl;
cout<<"\tPilihan (1 - 4) : ";
cin>>pilih;
cout<<endl<<endl;
pilihan();
cout<<"\t==============================="<<endl;
}
while(pilih!=4);
}
void pilihan()
{
if(pilih==1)
insert_data();
//3
else if(pilih==2)
delete_data();
else if(pilih==3)
display_data();
else
cout<<"Nomor tidak ada dalam menu";
{
cout<<"EXIT"<<endl;;
}
}
void buat_baru()
{
baru = new(node);
cout<<"Input Nim : ";cin>>baru->nim;
cout<<"Input Name : ";cin>>baru->nama;
cout<<"Input Gender : ";cin>>baru->gender;
cout<<"Input Nilai : ";cin>>baru->nilai;
cout<<"\n\t---Data berhasil disimpan---";
cout<<"\n\nPRESS ENTER TO CONTINUE...";
baru->prev=NULL;
baru->next=NULL;
}
void insert_data()
{
buat_baru();
if(head==NULL)
{
head=baru;
tail=baru;
}
else
{
//4
baru->next=head;
head=baru;
}
cout<<endl<<endl;
}
void delete_data()
{
int hapus,nim;
if(head==NULL)
{
cout<<"Linked List kosong"<<endl;
}
else
{
hapus=head->nim;
cout<<"Input data yang akan dihapus adalah ";
cin>>nim;
//5
hapus = head->nim;
head = head->next;
delete del;
cout<<"DATA TELAH BERHASIL DIHAPUS!!"<<endl;
}
}
void display_data()
{
if (head==NULL)
cout<<"\nData tidak dapat ditemukan!"<<endl;
else
{
help=head;
while(help!=NULL)
{
//6
cout<<" Nim : "<<help->nim<<endl;
cout<<" Nama : "<<help->nama<<endl;
cout<<" Gender : "<<help->gender<<endl;
cout<<" Nilai : "<<help->nilai<<endl;
help=help->next;
}
}
getch();
}
7. program linked list 2
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node
{
int info;
struct node *next;
}*last, *baru, *start=NULL, *tail=NULL,*help,*del;
int counter = 0;
class circular_link_list {
public:
void create_node(int data);
void add_begin(int data);
//buat fungsi untuk add after dengan parameter data dan position berikut :
void add_after(int data, int position);
//
void delete_element(int data);
void search_element(int data);
void display_list();
void update();
void sort();
circular_link_list()
{
last = NULL;
}
};
int main()
{
int pilihan, element, position;
circular_link_list cl;
while (1)
{
cout<<endl<<"---------------------------"<<endl;
cout<<endl<<"Circular singly linked list"<<endl;
cout<<endl<<"---------------------------"<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at beginning"<<endl;
cout<<"3.Add after"<<endl;
cout<<"4.Delete"<<endl;
cout<<"5.Display"<<endl;
cout<<"6.Quit"<<endl;
cout<<"Enter your pilihan : ";
cin>>pilihan;
switch(pilihan)
{
case 1 : cout<<"Enter the element: ";
cin>>element;
cl.create_node(element);
cout<<endl;
break;
case 2 : cout<<"Enter the element: ";
cin>>element;
cl.add_begin(element);
cout<<endl;
break;
//pemanggilan fungsi after position
case 3 : cout<<"Enter the element: ";
cin>>element;
cout<<"Insert element after position: ";
cin>>position;
cl.add_after(element, position);
cout<<endl;
break;
//
case 4 : if (last == NULL) {
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
cl.delete_element(element);
cout<<endl;
break;
case 5 : cl.display_list();
break;
case 6 : exit(1);
break;
default : cout<<"Wrong pilihan"<<endl;
}
}
return 0;
}
void circular_link_list::create_node(int data) {
struct node *temp;
temp = new(struct node);
temp->info = data;
if (last == NULL) {
last = temp;
temp->next = last;
} else {
temp->next = last->next;
last->next = temp;
last = temp; }
}
void circular_link_list::add_begin(int data) {
if (last == NULL) {
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->info = data;
temp->next = last->next;
last->next = temp;
}
void circular_link_list::delete_element(int data)
{
struct node *temp, *s;
s = tail->next;
if (tail->next == tail && tail->info == data) {
temp = tail;
tail = NULL;
free(temp);
return;
}
if (s->info == data)
{
temp = s;
tail->next = s->next;
free(temp);
return;
}
while (s->next != tail) {
if (s->next->info == data) {
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<data;
cout<<" deleted from the list"<<endl;
return;
}
s = s->next;
}
if (s->next->info == data) {
temp = s->next;
s->next = tail->next;
free(temp);
tail = s;
return;
}
cout<<"Element "<<data<<" not found in the list"<<endl;
}
void circular_link_list::display_list() {
struct node *s;
if (last == NULL) {
cout<<"List is empty"<<endl;
return;
}
s = last->next;
cout<<"Circular Link List: "<<endl;
while (s != last) {
cout<<s->info<<"->";
s = s->next;
}
cout<<s->info<<endl;
}
void circular_link_list::add_after(int data,int position)
{
if (last == NULL)
{
cout<<"Data kosong, Mohon Buat List Dahulu"<<endl;
return;
}
struct node *temp, *s;
s = last->next;
for (int i = 0;i < position-1;i++)
{
s = s->next;
if (s == last->next)
{
cout<<"List kurang dari : ";
cout<<position<<"list"<<endl;
return;
}
}
temp = new(struct node);
temp->next = s->next;
temp->info = data;
s->next = temp;
if (s == last)
{
last=temp;
}
}
2 program stack
1. program push stack
#include <iostream>
#include <stdio.h>
#include <conio.h>
#define size 5
using namespace std;
struct stack {
int a [size];
int top;
};
typedef struct stack STACK;
void push (STACK *p,int value)/*Push operation */
{
if (p->top==size-1)
cout<<"STACK IS FULL";
else
p->a[++p->top]=value;}
int pop (STACK *p)/*POP OPERATION*/
{
if (p->top==-1){
cout <<"STACK IS EMPTY";
return -1;
}
else
return p->a[p->top--];}
void display (STACK *p) /* DISPLAY OPERATION */
{
int i;
if (p->top==-1)
cout <<"\n STACK IS EMPTY\n";
else
cout << "\n STACK IS\n";
for (i=p->top;i>=0;i--)
cout <<p->a[i]<<"\n";
}
int main (){
STACK s;
int x,c,i;
s.top=-1;
do {
cout << "\n1 : To PUSH \n";
cout << "2 : To POP \n";
cout << "3 : To DISPLAY \n";
cout << "4 : To DESTROY \n";
cout << "5 : To EXIT \n";
cout << "\n\n EnterChoice \n";
cin>>c;
switch (c){
case 1 :
cout << "\nEnter element";
cin >>x;
push (&s,x);
break;
case 2 :
x=pop(&s);
if (x!=-1)
cout << "\n Element deleted ="<<x;
break;
case 3 :
display(&s);
break;
case 4 :
if(s.top==-1)
printf("STACK is destroying\n");
for (i=s.top;i>=0;--i)
printf("element destroyed are %d\n",pop(&s));
s.top=-1;
}printf ("STACK DESTROYED\n");
}while (c!=5);}
2. program stack pointer
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <malloc.h>
using namespace std;
typedef struct elmt *alamatelmt;
typedef struct elmt {
int isi;
alamatelmt next;
} Tstack;
typedef Tstack *stack;
void buatStack(stack *S){
(*S) = NULL;
}
void push (stack *S, int IB){
Tstack *NB;
NB = (Tstack *) malloc (sizeof (Tstack));
NB ->isi= IB;
NB->next = NULL;
if((*S) == NULL){
(*S)=NB;
}
else {
NB->next=(*S);
(*S)=NB;
}
}
void pop (stack *S,int &X){
Tstack *p;
X = (*S)->isi;
p = (*S);
if ((*S)!=NULL){
(*S)=(*S)->next;
}
free (p);
}
void cetak (stack S){
Tstack *p;
p=S;
while (p!=NULL){
cout << p->isi<<" ";
p=p->next;
}
}
main (){
int bil;
stack ST;
buatStack(&ST);
push(&ST, 26);
push(&ST, 12);
push(&ST, 21);
cout << "isi Stack mula mula : "<< endl;
cetak(ST);
cout<<endl;
for (int i=0;i<2;i++){
pop(&ST, bil);
cout << "yang diambil = "<<bil;
cout<<endl;
cout<<"Sisanya : ";
cetak(ST);
cout << endl;}
cout <<"\nIsi Stack sekarang : "<<endl;
cetak(ST);
/*cout<<"masukkan bilanga bulat : ";
cin >> bil;
while (bil !=0){
push (&ST, bil %2);
bil = bil/2;
}
cout <<"Bilangan Biner = ";
cetak (ST);*/
return 0;
}
99. CONTOH PROGRAM QUEUE 1
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iostream>
using namespace std;
typedef int ItemType;
typedef struct QueueNodeTag{
ItemType Item;
struct QueueNodeTag*Link;
}QueueNode;
typedef struct{
QueueNode *Front;
QueueNode *Rear;
}Queue;
void InitializeQueue(Queue *Q)
{
Q->Front=NULL;
Q->Rear=NULL;
}
int Empty(Queue *Q)
{
return(Q->Front==NULL);
}
int Full(Queue *Q)
{
return 0;
}
void Insert(ItemType R, Queue *Q)
{
QueueNode*Temp;
Temp=(QueueNode *)
malloc(sizeof(QueueNode));
if (Temp == NULL){
printf("Queue tidak dapat tercipta");
} else {
Temp->Item=R;
Temp->Link=NULL;
if(Q->Rear==NULL){
Q->Front=Temp;
Q->Rear=Temp;
}else{
Q->Rear->Link=Temp;
Q->Rear=Temp;
}
cout<<"\nItem dimasukkan: "<<R<<"\n";
}
}
void Remove( ItemType F, Queue *Q)
{
QueueNode *Temp;
if(Q->Front==NULL){
printf("Queue masih kosong!");
}else{
F=Q->Front->Item;
Temp=Q->Front;
Q->Front=Temp->Link;
free(Temp);
if(Q->Front==NULL)Q->Rear=NULL;
}
cout<<"\nItem dikeluarkan: "<<F<<"\n";
}
void Tampil(QueueNode *N) {
while (N !=NULL) {
printf("%5d", N->Item);
N=N->Link;
}
}
int main(){
Queue anam;
int Item;
anam.Front = anam.Rear = NULL;
Insert(100,&anam); Tampil(anam.Front);
Insert(200,&anam); Tampil(anam.Front);
Insert(300,&anam); Tampil(anam.Front);
cout<<"\n=====================================\n";
Remove(Item, &anam); Tampil(anam.Front);
Remove(Item, &anam); Tampil(anam.Front);
Remove(Item, &anam); Tampil(anam.Front);
return 0;
}
100. CONTOH PROGRAM QUEUE 2
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define maxqueue 100
using namespace std;
typedef int itemtype;
typedef struct{
int count;
int front;
int rear;
itemtype item[maxqueue] ;
} queue;
void initializequeue(queue *Q){
Q->count=0;
Q->front=0;
Q->rear=0;
}
int empty(queue *Q){
return Q->count=0;
}
int full(queue *Q){
return Q->count == maxqueue;
}
void insert(itemtype ins, queue *Q){
if (Q->count==maxqueue){
printf("Tidak dapat memasukkan data, Queue penuh!!");
}
else{
Q->item[Q->rear]=ins;
Q->rear = (Q->rear+1)%maxqueue;
++(Q->count);
}
}
void remove(queue *Q, itemtype *rm){
if(Q->count==0){
printf("Tidak dapat mengambil data! Queue kosong!!");
}
else{
*rm=Q->item[Q->front];
Q->front = (Q->front+1)%maxqueue;
--(Q->count);
}
}
void display(queue *Q){
if(Q->count==0){
cout<<"DATA KOSONG";
}else{
cout <<"Data dalam Queue : ";
for(int i=Q->front; i<=Q->rear-1;i++){
cout<<Q->item[i]<<" ";
}
}
}
int main(){
queue anam;
itemtype rm;
initializequeue(&anam);
insert(100, &anam);
display(&anam);
cout<<endl;
insert(200, &anam);
display(&anam);
cout<<endl;
insert(300, &anam);
display(&anam);
cout<<endl;
cout<<endl;
cout<<"REMOVE KE-1 BERJALAN"<<endl;
remove(&anam, &rm);
display(&anam);
cout<<endl;
cout<<"REMOVE KE-2 BERJALAN"<<endl;
remove(&anam, &rm);
display(&anam);
cout<<endl;
cout<<"REMOVE KE-2 BERJALAN"<<endl;
remove(&anam, &rm);
display(&anam);
cout<<endl;
return 0;
}
101. CONTOH PROGRAM QUEUE 3
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int itemtype;
typedef struct queuenodetag{
itemtype item;
struct queuenodetag *link;
}queuenode;
typedef struct{
queuenode *front;
queuenode *rear;
} queue;
void initializequeue(queue *Q){
Q->front=NULL;
Q->rear =NULL;
}
int empty(queue *Q){
return(Q->front==NULL);
}
int full(queue *Q){
return 0;
}
void insert(itemtype R, queue *Q){
queuenode *temp;
temp=(queuenode*)malloc(sizeof(queuenode));
if(temp == NULL){
cout<<"Queue tidak dapat tercipta";
}
else{
temp->item=R;
temp->link=NULL;
if(Q->rear=NULL){
Q->front=temp;
Q->rear=temp;
} else{
Q->rear->link=temp;
Q->rear=temp;
}
}
}
void remove(queue *Q, itemtype *F){
queuenode *temp;
if(Q->front==NULL){
cout<<"Queue Masih Kosong!!";
} else {
*F=Q->front->item;
Q->front = temp->link;
free(temp);
if(Q->front==NULL){
Q->rear=NULL;
}
}
cout<<"ITEM DIREMOVE !!!"<<endl;
}
void display(queuenode *Q){
while (Q!=NULL){
cout<<Q->item<<" ";
Q=Q->link;
}
}
int main(){
queue anam;
int data;
anam.front = anam.rear = NULL;
insert(100,&anam); display(anam.front);
insert(200,&anam); display(anam.front);
insert(300,&anam); display(anam.front);
cout<<"\n=====================================\n";
remove(&anam, &data); display(anam.front);
remove(&anam, &data); display(anam.front);
remove(&anam, &data); display(anam.front);
return 0;
}
102. CONTOH PROGRAM BINARY SEARCH TREE
/*
* C++ Program to Implement a Binary Search Tree using Linked Lists
*/
#include <iostream>
#include <conio.h>
using namespace std;
struct tree
{
tree *l, *r;
int data;
}*root = NULL, *p = NULL, *np = NULL, *q;
void create()
{
int value,c = 0;
while (c < 7)
{
if (root == NULL)
{
root = new tree;
cout<<"enter value of root node\n";
cin>>root->data;
root->r=NULL;
root->l=NULL;
}
else
{
p = root;
cout<<"enter value of node\n";
cin>>value;
while(true)
{
if (value < p->data)
{
if (p->l == NULL)
{
p->l = new tree;
p = p->l;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in left\n";
break;
}
else if (p->l != NULL)
{
p = p->l;
}
}
else if (value > p->data)
{
if (p->r == NULL)
{
p->r = new tree;
p = p->r;
p->data = value;
p->l = NULL;
p->r=NULL;
cout<<"Value entered in right \n";
break;
}
else if (p->r!=NULL)
{
p=p->r;
}
}
}
}
c++;
}
}
void inorder (tree *p)
{
if(p!=NULL)
{
inorder(p->l);
cout<<p->data<<endl;
inorder(p->r);
}
}
void preorder(tree *p)
{
if(p!=NULL)
{
cout<<p->data<<endl;
preorder(p->l);
preorder(p->r);
}
}
void postorder(tree *p)
{
if (p!=NULL)
{
postorder(p->l);
postorder(p->r);
cout<<p->data<<endl;
}
}
int main()
{
create();
cout<<"Printing traversal in inorder \n";
inorder(root);
cout<<"Printing traversal in preorder \n";
preorder(root);
cout<<"Printing traversal in postorder \n";
postorder(root);
getch();
}
103. CONTOH PROGRAM BINARY SEARCH TREE 2
#include <iostream>
using namespace std;
class BinarySearchTree{
private:
struct tree_node{
tree_node* left;
tree_node* right;
int data;
};
tree_node* root;
public:
BinarySearchTree(){
root = NULL;
}
bool isEmpty() const { return root==NULL; }
void print_preorder();
void preorder(tree_node*);
void insert(int);
};
// Smaller elements go left
// larger elements go right
void BinarySearchTree::insert(int d){
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if(isEmpty()) root = t;
else{
//Note: ALL insertions are as leaf nodes
tree_node* curr;
curr = root;
// Find the Node's parent
while(curr){
parent = curr;
if(t->data > curr->data)
curr = curr->right;
else
curr = curr->left;
}
if(t->data < parent->data)
parent->left = t;
else
parent->right = t;
}}
void BinarySearchTree::print_preorder(){
preorder(root);
}
void BinarySearchTree::preorder(tree_node* p){
if(p != NULL){
cout<<" "<<p->data<<" ";
if(p->left) preorder(p->left);
if(p->right) preorder(p->right);
}
else return;
}
int main(){
BinarySearchTree b;
int ch,tmp;
while(1){
cout<<endl<<endl;
cout<<" Binary Search Tree Operations "<<endl;
cout<<" ----------------------------- "<<endl;
cout<<" 1. Insertion/Creation "<<endl;
cout<<" 2. Pre-Order Traversal "<<endl;
cout<<" 3. Exit "<<endl;
cout<<" Enter your choice : ";
cin>>ch;
switch(ch){
case 1 : cout<<" Enter Number to be inserted : ";
cin>>tmp;
b.insert(tmp);
break;
case 2 : cout<<endl;
cout<<" Pre-Order Traversal "<<endl;
cout<<" -------------------"<<endl;
b.print_preorder();
break;
case 3 :
return 0;
}}}
104. CONTOH PROGRAM AVL TREE
/*
* C++ program to Implement AVL Tree
*/
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#define pow2(n) (1 << (n))
using namespace std;
/*
* Node Declaration
*/
struct avl_node
{
int data;
struct avl_node *left;
struct avl_node *right;
}*root;
/*
* Class Declaration
*/
class avlTree
{
public:
int height(avl_node *);
int diff(avl_node *);
avl_node *rr_rotation(avl_node *);
avl_node *ll_rotation(avl_node *);
avl_node *lr_rotation(avl_node *);
avl_node *rl_rotation(avl_node *);
avl_node* balance(avl_node *);
avl_node* insert(avl_node *, int );
void display(avl_node *, int);
void inorder(avl_node *);
void preorder(avl_node *);
void postorder(avl_node *);
avlTree()
{
root = NULL;
}
};
/*
* Main Contains Menu
*/
int main()
{
int choice, item;
avlTree avl;
while (1)
{
cout<<"\n---------------------"<<endl;
cout<<"AVL Tree Implementation"<<endl;
cout<<"\n---------------------"<<endl;
cout<<"1.Insert Element into the tree"<<endl;
cout<<"2.Display Balanced AVL Tree"<<endl;
cout<<"3.InOrder traversal"<<endl;
cout<<"4.PreOrder traversal"<<endl;
cout<<"5.PostOrder traversal"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Enter your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter value to be inserted: ";
cin>>item;
root = avl.insert(root, item);
break;
case 2:
if (root == NULL)
{
cout<<"Tree is Empty"<<endl;
continue;
}
cout<<"Balanced AVL Tree:"<<endl;
avl.display(root, 1);
break;
case 3:
cout<<"Inorder Traversal:"<<endl;
avl.inorder(root);
cout<<endl;
break;
case 4:
cout<<"Preorder Traversal:"<<endl;
avl.preorder(root);
cout<<endl;
break;
case 5:
cout<<"Postorder Traversal:"<<endl;
avl.postorder(root);
cout<<endl;
break;
case 6:
exit(1);
break;
default:
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
/*
* Height of AVL Tree
*/
int avlTree::height(avl_node *temp)
{
int h = 0;
if (temp != NULL)
{
int l_height = height (temp->left);
int r_height = height (temp->right);
int max_height = max (l_height, r_height);
h = max_height + 1;
}
return h;
}
/*
* Height Difference
*/
int avlTree::diff(avl_node *temp)
{
int l_height = height (temp->left);
int r_height = height (temp->right);
int b_factor= l_height - r_height;
return b_factor;
}
/*
* Right- Right Rotation
*/
avl_node *avlTree::rr_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->right;
parent->right = temp->left;
temp->left = parent;
return temp;
}
/*
* Left- Left Rotation
*/
avl_node *avlTree::ll_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
/*
* Left - Right Rotation
*/
avl_node *avlTree::lr_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->left;
parent->left = rr_rotation (temp);
return ll_rotation (parent);
}
/*
* Right- Left Rotation
*/
avl_node *avlTree::rl_rotation(avl_node *parent)
{
avl_node *temp;
temp = parent->right;
parent->right = ll_rotation (temp);
return rr_rotation (parent);
}
/*
* Balancing AVL Tree
*/
avl_node *avlTree::balance(avl_node *temp)
{
int bal_factor = diff (temp);
if (bal_factor > 1)
{
if (diff (temp->left) > 0)
temp = ll_rotation (temp);
else
temp = lr_rotation (temp);
}
else if (bal_factor < -1)
{
if (diff (temp->right) > 0)
temp = rl_rotation (temp);
else
temp = rr_rotation (temp);
}
return temp;
}
/*
* Insert Element into the tree
*/
avl_node *avlTree::insert(avl_node *root, int value)
{
if (root == NULL)
{
root = new avl_node;
root->data = value;
root->left = NULL;
root->right = NULL;
return root;
}
else if (value < root->data)
{
root->left = insert(root->left, value);
root = balance (root);
}
else if (value >= root->data)
{
root->right = insert(root->right, value);
root = balance (root);
}
return root;
}
/*
* Display AVL Tree
*/
void avlTree::display(avl_node *ptr, int level)
{
int i;
if (ptr!=NULL)
{
display(ptr->right, level + 1);
printf("\n");
if (ptr == root)
cout<<"Root -> ";
for (i = 0; i < level && ptr != root; i++)
cout<<" ";
cout<<ptr->data;
display(ptr->left, level + 1);
}
}
/*
* Inorder Traversal of AVL Tree
*/
void avlTree::inorder(avl_node *tree)
{
if (tree == NULL)
return;
inorder (tree->left);
cout<<tree->data<<" ";
inorder (tree->right);
}
/*
* Preorder Traversal of AVL Tree
*/
void avlTree::preorder(avl_node *tree)
{
if (tree == NULL)
return;
cout<<tree->data<<" ";
preorder (tree->left);
preorder (tree->right);
}
/*
* Postorder Traversal of AVL Tree
*/
void avlTree::postorder(avl_node *tree)
{
if (tree == NULL)
return;
postorder ( tree ->left );
postorder ( tree ->right );
cout<<tree->data<<" ";
}
105. CONTOH PROGRAM SELECTION SORT
#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
void print(int[], int);
void selection_sort(int [], int);
//selection sort
void selection_sort(int ar[], int size){
int min_ele_loc;
for(int i=0;i<9;++i){
//find minimum element in the unsorted array
//assume it's the first element;
min_ele_loc=i;
//loop through the array to find it
for(int j=i+1;j<10;++j){
if(ar[j]<ar[min_ele_loc]){ //found new minimum position
min_ele_loc=j;
}
}
//swap the values
swap(ar[i], ar[min_ele_loc]);
}
}
//print the array
void print(int temp_ar[], int size){
for(int i=0;i<size;++i){
cout<<temp_ar[i]<<" ";
}
cout<<endl;
}
//driver function
int main(){
int min_ele_loc;
int ar[]={10,2,45,18,16,30,29,1,1,100};
cout<<"Array Initially : ";
print(ar,10);
selection_sort(ar,10);
cout<<"Array after selection sort : ";
print (ar,10);
//return 0;
getch();
}
106. CONTOH PROGRAM BUBBLE SORT
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main(){
int nilai[8];
int temp;
cout<<"Data sebelum diurutkan"<<endl;
for(int ctr=0;ctr<8;ctr++){
cout<<"Masukkan Data ke "<<ctr+1<<" : ";
cin>>nilai[ctr];
}
cout<<endl;
cout<<endl;
for(int i=0;i<8;i++){
for(int ii=0;ii<8;ii++){
if(nilai[ii]>nilai[ii+1]){
temp=nilai[ii];
nilai[ii]=nilai[ii+1];
nilai[ii+1]=temp;
}
}
}
cout<<"Data setelah diurutkan"<<endl;
for(int iii=0;iii<8;iii++){
cout<<setw(3)<<nilai[iii]<<" ";
}
getch();
}
107. CONTOH PROGRAM INSERTION SORT
#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int data[10], data2[10];
int Max,i,j;
void straighinsertsort(){
int i,j,x;
for(i=1;i<=Max;i++){
x=data[i];
j=i-1;
while(x<data[j]){
data[j+1]=data[j]; //data [j] dimasukkan ke data [j+1]
j--;
}
data[j+1]=x; //x dimasukkan pada data[j+1]
}
}
int main(){
cout<<"PROGRAM INSERTION SORT \n"<<endl;
cout<<"Masukkan Jumlah Data : ";
cin>>Max;
for(int i=1;i<=Max;i++){
cout<<"Masukkan data ke "<<i<<" : ";
cin>>data[i];
data2[i]=data[i];
}
straighinsertsort();
cout<<"\n data setelah di sort : ";
for(i=1; i<=Max; i++){
cout<<" "<<data[i];
}
getch();
}
108. CONTOH PROGRAM QUICK SORT
#include <iostream>
#include <conio.h>
using namespace std;
void tampilkan_larik(int data[], int n)
{
int i;
for (i = 1; i <= n; i++)
cout << data[i] << " ";
cout << "\n";
}
int partisi(int data[], int awal, int akhir)
{
int x, i, j, simpan;
//x=data[awal];
i = awal;
j = akhir;
while (1)
{
while (data[i]<data[awal])
i = i + 1;
while (data[j]>data[awal])
j = j - 1;
if (i<j)
{
//tukarkan data
simpan = data[i];
data[i] = data[j];
data[j] = simpan;
}
else
return j;
}
}
void quick_sort(int data[], int awal, int akhir)
{
int q;
if (awal<akhir)
{
q = partisi(data, awal, akhir);
quick_sort(data, awal, q);
quick_sort(data, q + 1, akhir);
}
}
int main()
{
int i, j, n, data[100];
cout << "Masukkan Jumlah element Array :";cin>>n;
for (i = 1; i <= n; i++)
{
cout << "Masukkan Elemen ke-" << i << " :"<<endl;
cin >> data[i];
}
cout << "Data sebelum diurut: " << endl;
for (j = 1; j <= n; j++)
{
cout << data[j] << " ";
}
quick_sort(data, 1, n);
//hasil pengurutan
cout << endl;
cout << endl;
cout << "Data Setelah Di Urut Dengan QucikSort:\n";
tampilkan_larik(data, n);
getch();
}
109. CONTOH PROGRAM MERGE SORT
#include <iostream>
#include<conio.h>
using namespace std;
void merge(int low, int mid, int up);
void mergeSort(int low, int up);
int a[50];
int main()
{
int jumlahBil, i;
cout << "Masukkan Jumlah element Array : " << endl;
cin >> jumlahBil;
for (int i = 0; i<jumlahBil; i++)
{
cout << "Masukkan Elemen ke-" << i + 1 << " : " << endl;
cin >> a[i];
}
{
cout << "Data Setelah Di Urut Dengan Merge Sorting : "<<endl;
}
mergeSort(0, jumlahBil);
for (i = 1; i <= jumlahBil; i++)
cout << a[i] << " ";
cout << endl;
getch();
}
void merge(int low, int mid, int up)
{
int h, i, j, k;
int b[50];
h = low;
i = low;
j = mid + 1;
while ((h <= mid) && (j <= up))
{
if (a[h] < a[j])
{
b[i] = a[h];
h++;
}
else
{
b[i] = a[j];
j++;
}
i++;
}
if (h>mid)
{
for (k = j; k <= up; k++) {
b[i] = a[k];
i++;
}
}
else
{
for (k = h; k <= mid; k++)
{
b[i] = a[k];
i++;
}
}
for (k = low; k <= up; k++) a[k] = b[k];
}
void mergeSort(int low, int up)
{
int mid;
if (low<up)
{
mid = (low + up) / 2;
mergeSort(low, mid);
mergeSort(mid + 1, up);
merge(low, mid, up);
}
}
110. CONTOH PROGRAM SEKUENSIAL SEARCHING
#include <stdio.h>
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
int i, n, dt, posisi, ketemu = 0;
int data[100];
cout<<"berapa banyak data di dalam array : ";
cin>>n;
for (i=0; i<n; i++){
cout<<"masukkan data ke "<<i+1<<" = ";
cin>>data[i];
}
cout<<"data yang dicari : ";
cin>>dt;
for(i=0; i<n;i++){
if(data[i]== dt){
ketemu = 1;
posisi = i;
cout<<"data "<<data[i]<<"ditemukan di posisi = "<<posisi+1;
}
}
if(ketemu == 0)
cout<<"data tidak ditemukan";
}
111. CONTOH PROGRAM SEKUENSIAL SEARCHING
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <math.h>
using namespace std;
int main(){
int array[]={1,2,3,4,5}, i=0, x;
cout<<"masukkan data yang akan dicari adalah ";
cin>>x;
array[5]=x;
i=0;
while (array [i]!=x){
i++;
}
if(i<5){
cout<<"Data Ketemu";
} else
cout<<"data tidak ditemukan";
getch();
}
112. CONTOH PROGRAM SEKUENSIAL SEARCHING
#include <stdio.h>
#include <conio.h>
#include <iostream>
using namespace std;
int main(){
int larik[9]={1,12,3,4,10,6,7,11,9};
int i,n, x, posisi;
cout<<"Data yang ingin kamu cari?? = ";
cin>>x;
i=0;
posisi=0;
while(i<8 && larik[i]!=x){
i++;
}
if (larik[i]!=x)
cout<<"Maaf, data yang dicari tidak ada";
else if(larik[i]==x){
posisi=i+1;
cout<<"pada posisi ke "<<posisi;
}
}
113. CONTOH PROGRAM BINARY SEARCH
#include <conio.h>
#include <iostream>
using namespace std;
int main(){
const int arraySize = 5;
int target;
//Array size and value already known.
int array[arraySize] = {1,2,3,4,5};
int first, mid, last;
cout<<"Enter a target to be found : ";
cin>>target;
//initialize first and last variables.
first = 0;
last = 4;
while (first<=last){
mid = (first + last)/2;
if (target>array[mid]){
first = mid+1;
}
else if (target<array[mid]){
last = mid +1;
}
else{
first = last +1;
}
}
//when dividing can no longer proceed you ar left with the middle term.
//if the target equal that term you're are successful.
if(target==array[mid]){
cout<<"Target found "<<endl;
}
else {
cout<<"Target not found. "<<endl;
}
getch();
}
114. CONTOH PROGRAM BUBBLE ASCENDING
#include <cstdlib>
#include <conio.h>
#include <iostream>
#include <stdio.h>
using namespace std;
struct node{
int NIM[];
string Nama[], Alamat[];
char Prodi[];
}mhs;
int main(){
mhs.NIM[0]=33;
mhs.Nama[0]="Khaerul";
mhs.Alamat[0]="Boyolali";
mhs.Prodi[0]='T';
mhs.NIM[1]=11;
mhs.Nama[1]="Anam";
mhs.Alamat[1]="Klaten";
mhs.Prodi[1]='K';
mhs.NIM[2]=22;
mhs.Nama[2]="Arfan";
mhs.Alamat[2]="Cikarang";
mhs.Prodi[2]='E';
mhs.NIM[3]=44;
mhs.Nama[3]="Salamun";
mhs.Alamat[3]="Jakarta";
mhs.Prodi[3]='I';
/*
for(int i=0;i<8;i++){
for(int ii=0;ii<8;ii++){
if(nilai[ii]>nilai[ii+1]){
temp=nilai[ii];
nilai[ii]=nilai[ii+1];
nilai[ii+1]=temp;
}
}
}
*/
cout<<"Data setelah diurutkan"<<endl;
//for(int i=0;i<=3;i++){
cout<<mhs.NIM[0]<<endl;
// cout<<mhs.Nama[0]<<endl;
// cout<<mhs.Alamat[0]<<endl;
// cout<<mhs.Prodi[0]<<endl;
//}
return 0;
}
115. CONTOH PROGRAM BUBBLE DESCENDING
#include <cstdlib>
#include <conio.h>
#include <iostream>
#include <stdio.h>
using namespace std;
struct node{
int NIM[100];
string Nama[100], Alamat[100];
char Prodi[100];
}mhs;
int main(){
mhs.NIM[0]=33;
mhs.Nama[0]="Khaerul";
mhs.Alamat[0]="Boyolali";
mhs.Prodi[0]='T';
mhs.NIM[1]=11;
mhs.Nama[1]="Anam";
mhs.Alamat[1]="Klaten";
mhs.Prodi[1]='K';
mhs.NIM[2]=22;
mhs.Nama[2]="Arfan";
mhs.Alamat[2]="Cikarang";
mhs.Prodi[2]='E';
mhs.NIM[3]=44;
mhs.Nama[3]="Salamun";
mhs.Alamat[3]="Jakarta";
mhs.Prodi[3]='I';
for(int i=0;i<4;i++){
for(int ii=0;ii<4;ii++){
if(mhs.NIM[ii]<mhs.NIM[ii+1]){
int NIM =mhs.NIM[ii];
mhs.NIM[ii]=mhs.NIM[ii+1];
mhs.NIM[ii+1]=NIM;
string Na=mhs.Nama[ii];
mhs.Nama[ii]=mhs.Nama[ii+1];
mhs.Nama[ii+1]=Na;
string Al=mhs.Alamat[ii];
mhs.Alamat[ii]=mhs.Alamat[ii+1];
mhs.Alamat[ii+1]=Al;
char temp=mhs.Prodi[ii];
mhs.Prodi[ii]=mhs.Prodi[ii+1];
mhs.Prodi[ii+1]=temp;
}
}
}
cout<<"DATA SETELAH DIURUTKAN"<<endl;
cout<<"======================="<<endl;
for(int iii=0;iii<=3;iii++){
cout<<"Mahasiswa urutan ke "<<iii+1<<endl;
cout<<"NIM : "<<mhs.NIM[iii]<<endl;
cout<<"Nama : "<<mhs.Nama[iii]<<endl;
cout<<"Alamat : "<<mhs.Alamat[iii]<<endl;
cout<<"Prodi : "<<mhs.Prodi[iii]<<endl;
cout<<endl;
}
return 0;
}
7. program pembalik kata
#include <iostream>
#include <conio.h>
using namespace std;
main()
{
char kata[10000], bantu[10000];
int i, n, max;
cout<<"\nMasukkan kalimat (bila ada spasi gunakan underscore)\t: \n\n";cin>>kata;
i = 0;
max = 0;
while(kata[i] != NULL)
{
i++;
max++;
}
max--;
cout<<"\n"<<endl;
n = 0;
for(i=max; i>=0; i--)
{
bantu[n] = kata[i];
n++;
}
cout<<"\nKalimat awal\t: \n"<<kata<<endl;
cout<<"\nKalimat yang sudah dibalik\t: \n"<<bantu<<endl;
n = 0;
for(i=0; i<=max; i++)
{
if(kata[i] != bantu[i])
{
n++;
}
}
if(n != 0)
{
cout<<"\n\nKalimat ini Tidak mengandung Polindrom"<<endl;
}
else
{
cout<<"\n\nKalimat ini mengandung Polindrom"<<endl;
}
getch();
}
8. program pembalik kata
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
char kata[100];
int length;
cout<<"MASUKKAN KATA : ";
cin.getline(kata,100);
//PROSEDUR 1
length = strlen(kata);
cout<<"KATA SETELAH DIBALIK : ";
for(length=length-1;length>=0;length--){
cout<<kata[length];
}
cout<<endl;
//PROSEDUR 2
cout<<"KATA SETELAH DIBALIK : "<<strrev(kata);
return 0;
}
116. CONTOH PROGRAM DENGAN TABEL
#include <iostream>
#include <conio.h>
#include <string.h>
#include <windows.h>
using namespace std;
void judul();
char tanya();
void isi();
char huruf(float rat);
void gotoxy(int x, int y){
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void cetak(int a, int b, char *teks){
gotoxy(b,a);cout<<teks;
}
void cetakc(int a, char *teks){
gotoxy(40-((strlen(teks)/2)),a);cout<<teks;
}
int main(){
judul();
isi();
cout<<endl<<endl;
cout<<" Praktikum ASD";
getch();
}
void judul(){
cetakc(1,"DAFTAR NILAI");
cetakc(2,"PRODI TEKNIK INFORMATIKA");
cetak(7,2,"========================================================================");
cetak(8,2,"|");
cetak(8,5,"No");
cetak(8,8,"|");
cetak(8,12,"NIM");
cetak(8,19,"|");
cetak(8,25,"N A M A");
cetak(8,42,"|");
cetak(8,44,"UTS");
cetak(8,48,"|");
cetak(8,50,"UAS");
cetak(8,54,"|");
cetak(8,56,"TUGAS");
cetak(8,62,"|");
cetak(8,64,"NILAI HRF");
cetak(8,74,"|");
cetak(9,2,"========================================================================");
}
void isi(){
int nim,uts,uas,tugas,tot;
char nama[15],maxnm[15],minnm[15];
float rata,maxnil,minnil,ratkelas,totrat;
char jawab;
static int i = 1;
maxnil=0;minnil=100;totrat=0;
do{
gotoxy(2,9+i);cout<<"|";
gotoxy(5,9+i);cin>>i;
gotoxy(8,9+i);cout<<"|";
gotoxy(10,9+i);cin>>nim;
gotoxy(19,9+i);cout<<"|";
gotoxy(21,9+i);cin>>nama;
gotoxy(42,9+i);cout<<"|";
gotoxy(44,9+i);cin>>uts;
gotoxy(48,9+i);cout<<"|";
gotoxy(50,9+i);cin>>uas;
gotoxy(54,9+i);cout<<"|";
gotoxy(56,9+i);cin>>tugas;
gotoxy(62,9+i);cout<<"|";
tot=uts+uas+tugas;
rata=tot/3;
totrat=totrat+rata;
ratkelas=totrat/i;
if(rata>maxnil){
maxnil=rata;
strcpy(maxnm,nama);
}
if(rata<minnil){
minnil=rata;
strcpy(minnm,nama);
}
gotoxy(67,9+i);cout<<huruf(rata);
gotoxy(74,9+i);cout<<"|";
jawab=tanya();
if(jawab=='t'){
gotoxy(4,7+i);
cout<<"========================================================================";
gotoxy(2,11+i);cout<<"Jumlah data : "<<i;
gotoxy(2,12+i);cout<<"Rata kelas : "<<ratkelas;
gotoxy(2,13+i);cout<<"Nilai tertinggi : "<<maxnil;
gotoxy(28,13+i);cout<<"Nama : "<<maxnm;
gotoxy(2,14+i);cout<<"Nilai terendah : "<<minnil;
gotoxy(28,14+i);cout<<"Nama : "<<minnm;
}
i++;
}while(jawab!='t');
}
char tanya(){
char jw;
cetak(5,2,"input data lagi[Y/T]? : ");
cin>>jw;
cetak(5,2," ");
return(jw);
}
char huruf(float rat){
if(rat>80)
return('A');
else if(rat>70)
return('B');
else if(rat>60)
return('C');
else if(rat>50)
return('D');
else
return('E');
}