C++ Understanding Arrays (CUA)

An array is a structured data consisting of a number of elements that have the same data type. Array elements are arranged sequentially in computer memory. Arrays can be one-dimensional, two-dimensional, three-dimensional or multidimensional.


Array Implementation In C++

1. One Dimensional Array

A One-dimensional Array is nothing but a collection of identical elements arranged in a single row. These elements have the same data type, but the contents of the elements may be different.

The general form of declaring a one-dimensional array:

Tipe_data nama_variabel[ukuran]

Array Initialization:

Tipe_data nama_variabel[ukuran] = {elemen1, elemen2, elemen-n}

From the illustration above, we can implement it as follows:

int nilai[10] = {100, 56, 67, 3, 88, 66, 11, 16, 45}

Example 1.1:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Mencatat nilai minimum dan maksimum dalam array
*/

void main() {

float nilai[3], total;

//input nilai
for (int i=0; i < 3; i++) {
cout << "Nilai ke " << i+1;
cout << " = ";
cin >> nilai[i];
}

//jumlahkan nilai
for (int i=0; i < 3; i++) {
total += nilai[i];
}
cout << "Nilai Akhir " << total / 3;

getch();
}

Output:

Nilai ke 1 = 70
Nilai ke 2 = 80.5
Nilai ke 3 = 90.5
Nilai Akhir 80.3333

Example 1.2:

#include <iostream.h>
#include <conio.h>
#define LENGTH 5

/**
*bundet.com
*Mencari bilangan minimum dan maksimum dalam array
*/

void main() {
int nilai[LENGTH] = {67, 34, 12, 77, 88};

//asumsi nilai min dan max adalah elemen
//array pertama
int min = nilai[0], max = nilai[0];

for (int i = 1; i < LENGTH; i++) {
//mencari bilangan minimum
if (nilai[i] < max) {
min = nilai[i];
}

//mencari bilangan maksimum
if (nilai[i] > max) {
max = nilai[i];
}

}

cout << "\nNilai Minimum : " << min;
cout << "\nNilai Maksimum : " << max;

getch();
}

Output:

Nilai Minimum : 12
Nilai Maksimum : 88

2. Two-dimensional Array

Two-dimensional arrays are an extension of one-dimensional arrays. If a one-dimensional array consists of only one row and several columns of elements, then a two-dimensional array consists of several rows and several columns of elements of the same type.

Pay attention to the following illustration:


Implementation in C++

The general form of declaring a two-dimensional array:

Tipe_data nama_variabel[jumlah_baris][jumlah_kolom]

Array Initialization:

Tipe_data nama_variabel[jumlah_baris][jumlah_kolom] = {{elm1-1}, {elm-n-n}}

From the illustration above, we can implement it as follows:

int ar2[3][6] = {

{55, 2, 66, 166, 6, 16},
{66, 55, 4, 35, 23, 77},
{55, 55, 556, 511, 55, 51}

}

Example 2.1:

#include <iostream.h>
#include <conio.h>
#define ROWS 3
#define COLS 2

/**
*bundet.com
*Mencatat data penjualan pertahun
*/

void main() {

int tahun= 2010;
int cell = 10;
int penjualan[ROWS][COLS];

//input data penjualan
for (int i=0; i < ROWS; i++) {
cout << "\nPenjualan Tahun " << i+tahun;
cout << "\n--------------------\n";

for (int j=0; j < COLS; j++) {
cout << "Data ke-" << j+1;
cout << " = "; cin >> penjualan[i][j];
}
}

//cetak header tabel
cout << "Data penjualan pertahun\n";
cout << "-----------------------\n";

//output data penjualan
for (int i=0; i < ROWS; i++) {
cout << "\nTahun " << tahun+i;
cout << "\n----------------\n";

for (int j=0; j < COLS; j++) {
cout << j+1 << ") ";
cout << penjualan[i][j] << endl;
}
}

getch();
}

Output:

Penjualan Tahun 2010
--------------------
Data ke-1 = 20
Data ke-2 = 10

Penjualan Tahun 2011
--------------------
Data ke-1 = 80
Data ke-2 = 90

Penjualan Tahun 2012
--------------------
Data ke-1 = 30
Data ke-2 = 12
Data penjualan pertahun
-----------------------

Tahun 2010

Source:

STMIK El Rahma Yogyakarta Module. By  Eding Muh. Saprudin, S.Kom

Other Version Notes

As explained in previous chapters, arrays can be used to store multiple data of the same type in one variable name. Defining arrays in C++ is almost similar to VB or Java. Only the writing syntax is different. Consider the following simple array example.

Example 9.23. Simple array

#include <iostream>

using namespace std;
 int main() {
  // deklarasi array A dengan 5 buah elemen bertipe int   int A[5];
  cout<<"A[C]"<<"   "<<"B"<<endl;   // Memasukkan nilai ke dalam elemen array   for (int C=0; C<5; C++) {   double B = 5;   A[C] = C;   B = A[C]/B;
    cout<<A[C]<<"     "<<B<<endl;
  }   return 0; }

In the example above we declare an array with the name A and its data type is int. C in the code above is a counter variable. To insert a value into the array, pay attention to the line A[C] = C. C here is the index of the variable A. Just like in VB or Java, the initial default value of the array index is 0. If the example above is run, the output will look like Figure 9.6.


Figure 9.6. Output of the execution of a simple array program.

In example 9.23 above we declare an array without initializing the value. But actually we can directly give a value together with the declaration of the array variable. Then we can change the value while the program is running or in another part of the program. Consider example 9.24 below.

Example 9.24. Declaring and initializing an array

#include <iostream>

using namespace std;
 int main() {
  // Deklarasikan dan inisialisasi array    char X[3] = { 'A', 'B', 'C' };

  // Menampilkan nilai awal elemen array   cout<<"Nilai array awal"<<endl;   cout<<"X[0] = "<<X[0]<<endl;   cout<<"X[1] = "<<X[1]<<endl;   cout<<"X[2] = "<<X[2]<<endl;

  // Mengubah elemen ke-1 dan ke-2
  X[0] = 'G';
  X[1] = 'H';

  // Menampilkan nilai perubahan dari elemen array   cout<<"Nilai array setelah dirubah"<<endl;   cout<<"X[0] = "<<X[0]<<endl;   cout<<"X[1] = "<<X[1]<<endl;   cout<<"X[2] = "<<X[2]<<endl;
   return 0; }

If we run the program code above, the results will appear as in Figure 9.7.


Figure 9.7. Results of executing array declaration and initialization.

C++ also provides a feature for creating multidimensional arrays. Declaring a multidimensional array can be done in the manner shown in example 9.25.

Example 9.25. Declaring a multidimensional array

#include <iostream>

using namespace std;
 int main() {

  // Deklarasi dan inisialisasi array multidimensi    int Matrik_A[3][2] = { {1,2}, {3,4}, {5,6} };   int Matrik_B[2][3] = { {1,2,3}, {4,5,6} };

  // Mendeklarasikan variabel untuk indeks pengulangan   int j, k;

  // Menampilkan nilai yang tersimpan dalam elemen array A   cout<<"ISI MATRIKS A"<<endl;   for (j=0; j<3; j++) {     for (k=0; k<2; k++) {
      cout<<"Matrik A["<<j<<"]["<<k<<"] =
"<<Matrik_A[j][k]<<endl;
    }     cout<<endl;
  }

  // Menampilkan nilai yang tersimpan dalam elemen array B   cout<<"ISI MATRIKS B"<<endl;   for (j=0; j<2; j++) {     for (k=0; k<3; k++) {
      cout<<"Matrik B["<<j<<"]["<<k<<"] =
"<<Matrik_B[j][k]<<endl;
    }     cout<<endl;
  }        return 0; }

In the example above, there are two multidimensional arrays, namely Matrix_A and Matrix_B. Both are two-dimensional matrices. Matrix_A has 3 rows and 2 columns while Matrix_B has 2 rows and 3 columns. The filling of the array element values ​​is done at the time of declaration. However, you can fill it using keyboard input via the cin command. The execution results of the program above will appear as in Figure 9.8.


Figure 9.8. Results of executing a multidimensional array.

Array is a data type that can hold a number of elements with the same data type. Accessing array elements can be done by mentioning the array name and index or element number. In programming, arrays can be distinguished into single-dimensional arrays and multi-dimensional arrays.

1. One Dimension Array

A one-dimensional array is an array that has one index type or one subscript number.

2. Defining Array Types

In C++ the general form is like this:

Tipe_data nama_variabel_array[jumlah_elemen_array];

Example:

int Nilai[5];

The example above defines an array variable with a value name that has five elements, where the element number starts from 0 and is described like this:

In C++, element numbers always start with 0. Element numbering is given automatically by C++, so that what we specify when defining an array is only the number of elements.

3. Operations on Arrays

Nilai[0] = 10;

So the meaning of the code above is: "enter data 10 into the array at element number 0", described like this:

Now we try to fill in the same value in element no.3, the method is like this:

Nilai[3] = Nilai[0];

Please translate the code above yourself, you should already know, okay, here's the picture:

Example 1

Pseudocode input_Data_Array

//akan dimasukan 5 data dalam array dan mencetaknya

//deklarasi array (tipe dan jumlah elemen)
int nilai[5]

//deskripsi
{
//membaca data
read(nilai[1])
read(nilai[2])
read(nilai[3])
read(nilai[4])
read(nilai[5])

//menampilkan data
write(nilai[1])
write(nilai[2])
write(nilai[3])
write(nilai[4])
write(nilai[5])
}

Program:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Array Dimensi Satu
*/

void main()
{
clrscr(); //untuk menghapus tampilan layar
int nilai[5];

cout<<"Masukan lima data nilai"<<endl;
cout<<"======================="<<endl;
cout<<"Nilai 1 : "; cin>>nilai[0];
cout<<"Nilai 2 : "; cin>>nilai[1];
cout<<"Nilai 3 : "; cin>>nilai[2];
cout<<"Nilai 4 : "; cin>>nilai[3];
cout<<"Nilai 5 : "; cin>>nilai[4];
cout<<endl;

cout<<"Data nilai yang anda masukan "<<endl;
cout<<"1    2    3    4    5"<<endl<<endl;
cout<<nilai[0]<<"    ";
cout<<nilai[1]<<"    ";
cout<<nilai[2]<<"    ";
cout<<nilai[3]<<"    ";
cout<<nilai[4]<<"    "<<endl;
getch();
}

Output

Example 2

In filling data into array elements repeatedly can be done with "for". The example program above will be replaced by entering data using "for".

Pseudocode

~//Input data array dengan for
//Akan dimasukan 5 data dalam array dan mencetaknya

//Deklarasi
int i;
int nilai[5];

//Deskripsi
{
  //membaca data
  for(i=0;i<5;i++)
  read(nilai[i])

  //menampilkan data
  for(i=0;i<5;i++)
  write(nilai[3])
} ~

Program:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Array dimensi satu dengan "for"
*Copyright Eko Riswanto ST.
*/

void main()
{
   clrscr(); //menghapus layar
   int nilai[5];

   cout<<"Masukan lima data nilai"<<endl;
   cout<<"======================="<<endl;
   for (int i=0; i<5; i++)
   {
   cout<<"Nilai ke "<<(i+1)<<" : ";
   cin>>nilai[i];
   }
   cout<<endl;
   cout<<"Data yang anda masukan"<<endl;
   cout<<"1    2    3    4    5"<<endl;
   cout<<"====================="<<endl;
   for (int i=0; i<5; i++)
   {
   cout<<nilai[i]<<"    ";
   }
   getch();
}

Output

The next example is finding the largest and smallest values ​​from a number of data entered into an array variable.

Program:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Array dimensi 1 "for"
*/

void main()
{
 int jum;
 int nilai[20];
 cout<<"jumlah data : ";
 cin>>jum;

 for (int i=0;i<jum;i++)
 {
  cout<<"Data ke - "<<i+1<<" : ";
  cin>>nilai[i];
 }

 //nilai pertama array dianggap sebagai
 //data terkecil dan data terbesar

 int min;
 min = nilai[0];
 int maks;
 maks = nilai[0];

 for(int i=0;i<jum;i++)
 {
  if (nilai[i] < min)
   min = nilai[i];
  if (nilai[i] > maks)
   maks = nilai[i];
 }

 cout<<"Nilai Terkecil : "<<min<<endl;
 cout<<"Nilai Terbesar : "<<maks<<endl;
 getch();
}

Output

Source:

© STMIK El Rahma Yogyakarta. Compiled by Mr. Eko Riswanto, ST, M.Cs,

Question 1

RY HAZIZI Oct 17, 2016, 06:03:00 Steady

YUSUF GREZZ6 Apr 2017, 16:37:00 Sir, how do you add up the results of a 2-dimensional array?

5 5 5 5 = 20
6 6 6 6 = 24

For something like that, sir, please enlighten me..thank you

ISNAINI Apr 24, 2017, 10:56:00 is there an example of an algorithm and flowchart for arrays?

C++ How to Display the Contents of a One Dimensional Array Element

Arrays or in other terms are often called arrays or some also call them indexed variables, because they are composed of several elements, each of which has an index and for arrays the index starts from 0, as a basis we will start from a one-dimensional array, here we will try to display the contents of each array element by inputting its index.

Initially, we do this stage by manually inputting the array contents into the program, so that we input each array one by one. Consider the following example:

Example 1a:

Program 1a:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Menampilkan isi array dimensi satu
*/

void main()
{
clrscr(); //untuk menghapus tampilan layar
int nilai[5];

cout<<"Masukan lima data nilai"<<endl;
cout<<"======================="<<endl;
cout<<"Nilai 1 : "; cin>>nilai[0];
cout<<"Nilai 2 : "; cin>>nilai[1];
cout<<"Nilai 3 : "; cin>>nilai[2];
cout<<"Nilai 4 : "; cin>>nilai[3];
cout<<"Nilai 5 : "; cin>>nilai[4];
cout<<endl;

cout<<"Data nilai yang anda masukan "<<endl;
cout<<"1    2    3    4    5"<<endl<<endl;
cout<<nilai[0]<<"    ";
cout<<nilai[1]<<"    ";
cout<<nilai[2]<<"    ";
cout<<nilai[3]<<"    ";
cout<<nilai[4]<<"    "<<endl;
getch();
}

Or like this;

Example 1b:

Program 1b:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Menampilkan isi array dimensi satu "for"
*/

void main(){
clrscr(); //menghapus layar
   int nilai[5];

   cout<<"Masukan lima data nilai"<<endl;
   cout<<"======================="<<endl;
   for (int i=0; i<5; i++)
   {
   cout<<"Nilai ke "<<(i+1)<<" : ";
   cin>>nilai[i];
   }
   cout<<endl;
   cout<<"Data yang anda masukan"<<endl;
   cout<<"1    2    3    4    5"<<endl;
   cout<<"====================="<<endl;
   for (int i=0; i<5; i++)
   {
   cout<<nilai[i]<<"    ";
   }
   getch();
}

Example 2:

Program 2:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Menampilkan isi array
*/

void main(){
 int a[] = {90, 95, 78, 85};
 int i;
 for(int k=0; k<4; k++){
 cout<<"Masukan larik 0-4 = ";
 cin>>i;cout<<endl;
 cout<<"isi larik adalah : ";
 cout<<a[i]<<endl;
 }
   getch();
}

Input data with looping, the next stage is to input the number of array elements and the data as we wish, this one is more responsive.

Example 3:

Program 3:

#include <iostream.h>
#include <conio.h>

/**
*bundet.com
*Menampilkan isi array
*/

void main(){
 int a[1];
 int i,j;

   cout<<"Jumlah elemen yang di inginkan : ";
   cin>>j;
   for(int k=0; k<j; k++){
   cout<<"indek ke-"<<k<<":";
   cin>>i;
   a[k]=i;
   }
   cout<<endl;
   cout<<"isi larik adalah : ";
   for(int k=0; k<j; k++){
   cout<<a[k]<<"-";
 }
 getch();

}

Hope this is useful & happy learning!

Question 1

FERRY RUDIYANTO 8 Jan 2015, 16:17:00 Just a suggestion, bro, for program number 1 it will be limited to 3 (number <4) selections, for example, it will display array number one twice, it can't be done because it is limited to using a for loop and for the data selection it should only be 0-3 because the array only goes up to 3, maybe it would be more appropriate to use a do while loop like this

include
#include
//www.gatewan.com
void main(){
int a[] = {90, 95, 78, 85};
int i;
do
{
cout<<"Masukan larik 0-3 = ";cin>>i;
if(i!=4){
cout<<"isi larik adalah : ";
cout<

Response 1

ok thanks friend... hehehe.. your presentation program is ready to be published man..

C++ Array Concept

Array variables have been touched upon in the previous section, but are still very limited. In this section we will learn more about arrays.

1. Understanding Arrays

The variables we have been using so far are ordinary variables that have the property that a variable name can only state a numeric or string value at a time. If we want to give a new value to the variable, the old value will be lost and replaced by the new value. What if we want to store several values/data in a variable with the same name, but all values ​​remain stored? The solution that can be done is to use an index on the variable name. This method is commonly called an array.

An array is a data structure that stores a collection of elements of the same type, each element is accessed directly through its index. The array index must be a data type that indicates ordering, such as an integer or a string. An array can be likened to a cupboard or locker that has a series of storage boxes that are numbered sequentially (see Figure 5.21). To store or retrieve something from a particular box, we only need to know the box number.


Figure 5.21. A cupboard with many drawers inside.

In array variables, we not only determine the data type, but also the number of elements of the array or in this case the upper limit of the index. In many programming languages ​​such as C++, Visual Basic, and several others, the initial index value is 0 not 1. How to write array variables varies depending on the programming language used. But what is certain is that the data type must be stated and the upper limit of the index must be determined. To fill data in an array, we can directly determine at what index we will fill it in as well as to call or display data from the array.

An example of declaring, filling and calling an array is as follows.

Arrays in C++

#include <iostream>
using namespace std;
int main() {
// Mendeklarasikan array A
dengan 3 buah elemen bertipe
int
int A[3];
// Mengisikan nilai elemen
array
A[0] = 5;
A[1] = 10;
A[2] = 20;
// Menampilkan nilai elemen
array
cout<<"Nilai elemen ke-1 =
"<<A[0];
cout<<"Nilai elemen ke-2 =
"<<A[1];
cout<<"Nilai elemen ke-3 =
"<<A[2];
return 0;
}

Arrays in Visual Basic

'Mendeklarasikan array A
dengan 3 buah elemen bertipe
integer
Dim A (2) as Integer

'Mengisikan nilai elemen
array
A(0) = 5;
A(1) = 10;
A(2) = 20;

'Menampilkan nilai elemen
array
Print A(0);
Print A(1);
Print A(2);

Pay attention to the two codes above. In the declaration of the array variable, the maximum index value is 2 but the number of elements is 3 because the index starts from 0, not from 1.

2. Searching Data in Array

One of the problems often encountered in arrays is how to find a particular element of the array. For example, in the case of the locker in Figure 5.21 above, there are 100 boxes available. Then we are asked to find the box number owned by a student named "Rudi". Another example, suppose there are many students in one school and we are asked to find data on a student with a certain name or a certain address. Consider the following example.

Example 5.24. Searching on an array


Example 5.24. Searching on an array

In this example, we are asked to find an element containing the number 12 from a set of elements in an array. There are 6 elements in the array. What do you think the algorithm is for solving it?

The most common and easiest way to do this is by using a linear search. In the past, this method was considered inefficient because it took a long time. However, with the rapid development of computers, the execution time of this algorithm is not a big problem. This method is done by comparing the contents of the elements with what we are looking for. One by one starting from the earliest element.

If we apply it to Example 5.24, then the program execution will take place sequentially as follows:

  • Set the number we want to find (i.e. 12)
  • Take the first element (i.e. A[0]), compare the contents of that element (i.e. 23) with the number we are looking for. If they are the same then stop.
  • If not then continue with the next element (i.e. A[1]), compare the contents of that element with the number we are looking for. If they are the same then stop.
  • If not, then continue with the next element. And so on until an element is found that contains the same number as the one we are looking for.

Example 5.24 will give the result of element A[3] which has a content of 12. If depicted in flowchart form, it will look like Figure 5.22.


Figure 5.22. Flowchart for searching numbers

In the flowchart in Figure 5.22, we use the While model repetition. There are two conditions that must be met here, namely  I < N dan Bil[I] <> A. The meaning of this condition is if the index value I is less than the upper limit of the index and the contents of  Bil[I] are not the same as the number we are looking for, then the search will continue at a higher index. As long as this condition is met, the search will continue. Note that here we use "and" which means that both conditions must be met to be considered true. The search will only stop if one or both conditions are no longer met. So, for example, if  Bil[I] it has the same contents as A, the search will stop because the conditions in While are no longer met.

3. Sorting Data in Arrays

Another problem in arrays that is also widely used is how to sort the elements of the array variable. Look again at Example 5.24. In the example, it can be seen that the contents of the elements of the array are not in sequential positions. How can the contents of the elements be sorted from largest to smallest or vice versa?

There are several algorithms that can be used to sort a set of numbers, including bubble sort, selection sort, shell sort, quick sort, and others. In this book we will discuss one algorithm, namely bubble sort. Although its performance is not as good as other algorithms, this algorithm is easy to understand and widely used. Consider the following example.

Example 5.24. Sorting with bubble sort

Suppose an array variable named Bil consists of 5 elements, each containing the number "5 1 4 2 8". Sort from the smallest value to the largest.

Solution:

We will use the bubble sort method to sort this array. Bubble sort is done by comparing two numbers that are in sequence. If the sequence is correct, then continue by comparing the next two numbers. If not, then swap the positions of the two numbers.

Let's apply this algorithm. Consider the following array table. The initial condition is at position J = 0. First we compare between  Bil[0] with  Bil[1].  Bil[0] = 5 while  Bil[1] = 1. Based on the bubble sort rule, the contents of  Bil[0] are not in the correct position because they are greater than the contents of  Bil[1]. So we need to swap the contents of these two array elements. So  Bil[0] = 1 and  Bil[1] = 5 (note the row at J = 1). The next step we compare  Bil[1] with  Bil[2].  Bil[1] = 5 and  Bil[2] = 4, so we have to swap the contents of these elements again (note the row J = 2). This continues until the comparison  Bil[3] with  Bil[4].

At the end of the table above, we see that the numbers are not completely sorted. Because we have only used one round as  Bil[0] a reference. We will do another comparison, but with  Bil[1] a reference. This is because  Bil[0] it must contain the smallest number. So we make a new table like this.

In the table position above, the sequence of numbers is actually correct, but the algorithm has not stopped because the algorithm has not checked the next round. So two more rounds are needed with the basis of each comparison being Bil[2] and  Bil[3]. The two tables are as follows.

If depicted in flowchart form it will look like Figure 5.23.


Figure 5.23. Flowchart for sorting numbers


Post a Comment

Previous Next

نموذج الاتصال