5 CONTOH PROGRAM ARRAY PADA C++
5 CONTOH PROGRAM ARRAY PADA C++
1. PROGRAM ARRAY SATU DIMENSI
PROGRAM :#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;
}
FLOWCHART :
2. PROGRAM ARRAY DUA DIMENSI
PROGRAM :#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";}}
FLOWCHART :
3. PROGRAM PENGGUNAAN ARRAY
PROGRAM :#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;
}
FLOWCHART :
4. PROGRAM ARRAY MULTI DIMENSI
PROGRAM :#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;
}
FLOWCHART :
5. PROGRAM POINTER ARRAY
PROGRAM :#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;
}
FLOWCHART :