350 likes | 829 Views
Array dalam C++. Teknik Elektro Sekolah Tinggi Teknologi Adisutjipto 2013. C++ Arrays. Array = grup lokasi memori . Grup tersebut sifatnya berurutan. Anggota grup = elemen array Tipe tiap elemen sama Array int, double, char, … Tiap elemen dibedakan berdasar nomor posisi (indeks).
E N D
Array dalam C++ TeknikElektro SekolahTinggiTeknologiAdisutjipto 2013
C++ Arrays • Array = grup lokasi memori. • Grup tersebut sifatnya berurutan. • Anggota grup = elemen array • Tipe tiap elemen sama • Array int, double, char, … • Tiap elemen dibedakan berdasar nomor posisi (indeks).
Memori & Array 4 bytes Tiap int = 4 bytes larik[0] larik[1] int larik[6]; larik[5]
C++ Arrays start at 0 !!!!!!! • Elemen pertama = elemen ke-0. • Jika array memiliki elemen sebanyak n, maka elemen terakhir adalah n-1. • Mengakses elemen ke-n = error.
Array Subscripts • Nomor elemen disebut dengan subscript. foo[i] Nama array subscript Subscript berupa ekspresi integer. Contoh subscript yang benar: foo[17] foo[i+3] foo[a+b+c]
Contoh Array #include<stdio.h> int main() { int square[100]; int i; int k; for(i=0;i<10;i++) { k=i+1; square[i]=k*k; printf(“\nPangkat dari %d adalah %d “,k,square[i]) } return 0; }
Deklarasi Array tipe_elemen nama_array[banyak_elemen]; tipe_elemen berupa variabel dalam C++ nama_array berupa nama variabel valid banyak_elemen berupa ekspresi integer
Inisialisasi • Inisialisasi array dilakukan ketika dideklarasikan (seperti pendeklarasian variabel) int angka[5] = {1,8,3,6,12}; float d[2] = {0.707, 0.707}; char s[] = {'R', 'P', 'I' };
Fungsi Cetak Array Can pass an array as a parameter. You don't have to say how big it is! void cetak_array(int a[], intpjg) { for (int i=0;i<pjg;i++) cout << "[" << i << "] = " << a[i] << endl; }
print_array() for doubles void cetak_array(float a[], intpjg){ for (int i=0;i<pjg;i++) cout << "[" << i << "] = " << a[i] << endl; }
Which is it? • We now have two functions with the same name: void print_array(double a[], intlen); void print_array(int a[], intlen); This is fine – as long as the prototypes are different everything works. This is called "overloading", using the same name for two (or more) different functions.
Arrays of char are special C++ provides a special way to deal with arrays of characters: char string1[] = “STuDY without U is like not complete"; char arrays can be initialized with string literals.
Arrays of Arrays • You can create an array of arrays: int a[2][2]; for (int i=0;i<2;i++) for (int j=0;j<2;j++) a[i][j] = i+j;
2-D Memory Organization { A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] A[2][0] A[2][1] A[2][2] A[3][0] A[3][1] A[3][2] char A[4][3]; A[0] A[1] A[2] A[3] { A is an array of size 4. Each element of A is an array of 3 chars { {
C++ does not have bounds checking Memory int a[6]; int foo; a[0] a[1] a[2] a[3] a[4] a[5] foo This is the array This is something else