Basic Cpp: Arrays

Arrays:

Array adalah list dari element yang mempunyai type yang sama. Untuk menggunakan array, kita perlu mendeklarasikan sesuai syntax berikut:

Deklarasi Arrays

type arrayName [ arraySize ];

arraySize, syaratnya:

1. harus bertipe integer dan tidak boleh 0 tapi [] diperbolehkan.

2. arraySize tidak dapat diubah lagi setelah dibuat.

type: C++ data type.

Contoh:

double balance[10];

Initial Arrays

Aturan C++, nilai dari element adalah undefined setelah deklarasi, jadi kita harus menginitial sebelum menggunakannya.

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

Memberi nilai pada Arrays

1. Menggunakan index, jangan lupa index dimulai dengan angka 0.

int balance[5] = {0,1,2,3,4}
balance[4] = 4

2. Menggunakan Loop

Contoh:

#include <iostream>
#include <iomanip>
#include <cmath>
#define SIZE 7
using namespace std;
 
int main() {
   int marks[] = {74, 43, 58, 60, 90, 64, 70};
   int sum = 0;
   int sumSq = 0;
   double mean, stdDev;
   for (int i = 0; i < SIZE; ++i) {
      sum += marks[i];
      sumSq += marks[i]*marks[i];
   }
   mean = (double)sum/SIZE;
   cout << fixed << "Mean is " << setprecision(2) << mean << endl;
 
   stdDev = sqrt((double)sumSq/SIZE - mean*mean);
   cout << fixed << "Std dev is " << setprecision(2) << stdDev << endl;
 
   return 0;
}

Hasil:

Mean is 65.57
Std dev is 13.56

Arrays Dua Dimensi

Deklarasi:

type arrayName [ x ][ y ];

x adalah row index
y adalah column index

Contoh:

int a[3][4] = {  
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

Mengakses 2 Dimensi Arrays:

#include <iostream>
using namespace std;
 
int main () {
   // an array with 5 rows and 2 columns.
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
 
   // output each array element's value                      
   for ( int i = 0; i < 5; i++ )
      for ( int j = 0; j < 2; j++ ) {
      
         cout << "a[" << i << "][" << j << "]: ";
         cout << a[i][j]<< endl;
      }
 
   return 0;
}

Hasil:

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

String

di C, String adalah array dari char yang diakhiri dengan karakter NULL  '\0'

sedangkan di C++, menyediakan class string

#include <iostream>
using namespace std;
 
int main() {
   char msg[256]; // Hold a string of up to 255 characters (terminated by '\0')
 
   cout << "Enter a message (with space)" << endl;
   cin.getline(msg, 256);  // Read up to 255 characters into msg
   cout << msg << endl;
 
   // Access via null-terminated character array
   for (int i = 0; msg[i] != '\0'; ++i) {
      cout << msg[i];
   }
   cout << endl;
 
   cout << "Enter a word (without space)" << endl;
   cin >> msg;
   cout << msg << endl;
 
   // Access via null-terminated character array
   for (int i = 0; msg[i] != '\0'; ++i) {
      cout << msg[i];
   }
   cout << endl;
   return 0;
}

 

Array dan Function

1. Array sebagai parameter

a. Menggunakan unsized array dan ArraySize pada function declaration dan function prototype

//function prototype
void myFunction(int param[], ArraySize);

// function declaration
void myFunction(int param[], ArraySize) {
   .
   .
}

Contoh:

/* Function to compute the sum of an array (SumArray.cpp) */
#include <iostream>
using namespace std;
 
// Function prototype
// Need to pass the array size too
int sum(int array[], int size);    
void print(int array[], int size);
 
// Test Driver
int main() {
   int a1[] = {8, 4, 5, 3, 2};
   print(a1, 5);   // {8,4,5,3,2}
   cout << "sum is " << sum(a1, 5) << endl;  // sum is 22
}
 
// Function definition
// Return the sum of the given array
int sum(int array[], int size) {
   int sum = 0;
   for (int i = 0; i < size; ++i) {
      sum += array[i];
   }
   return sum;
}
 
// Print the contents of the given array
void print(int array[], int size) {
   cout << "{";
   for (int i = 0; i < size; ++i) {
      cout << array[i];
      if (i < size - 1) {
         cout << ",";
      }
   }
   cout << "}" << endl;
}
Average value is: 214.4

2. Pass by value atau pass by reference?

Array didesign menggunakan pass by reference, yang akan mengakibatkan nilai array diluar function akan berubah, jika tidak mau merubahnya gunakan const

/* Search an array for the given key using Linear Search (LinearSearch.cpp) */
#include <iostream>
using namespace std;
 
int linearSearch(const int a[], int size, int key);
 
int main() {
   const int SIZE = 8;
   int a1[SIZE] = {8, 4, 5, 3, 2, 9, 4, 1};
 
   cout << linearSearch(a1, SIZE, 8) << endl;  // 0
   cout << linearSearch(a1, SIZE, 4) << endl;  // 1
   cout << linearSearch(a1, SIZE, 99) << endl; // 8 (not found)
}
 
// Search the array for the given key
// If found, return array index [0, size-1]; otherwise, return size
int linearSearch(const int a[], int size, int key) {
   for (int i = 0; i < size; ++i) {
      if (a[i] == key) return i;
   }
   return size;
}

 

Return Local Array dari Function

#include <iostream> 
using namespace std; 

int* fun() 
{ 
  int arr[100]; 

  /* Some operations on arr[] */
  arr[0] = 10; 
  arr[1] = 20; 

  return arr; 
} 

int main() 
{ 
  int* ptr = fun(); 
  cout << ptr[0] << " " << ptr[1]; 
  return 0; 
} 

Warning:

In function 'int* fun()':
6:8: warning: address of local variable 'arr' returned [-Wreturn-local-addr]
    int arr[100];
        ^

Output:

10 20

The above program is WRONG. It may produce values 10 20 as output or may produce garbage values or may crash. The problem is, we return address of a local variable which is not advised as local variables may not exist in memory after function call is over.

So in simple words, Functions can’t return arrays in C. However, inorder to return the array in C by a function, one of the below alternatives can be used.

Following are some correct ways of returning array:

Using Dynamically Allocated Array :

Dynamically allocated memory (allocated using new or malloc()) remains their until we delete it using delete or free(). So we can create a dynamically allocated array and we can delete it once we come out of function.

#include <iostream> 
using namespace std; 

int* fun() 
{ 
  int* arr = new int[100]; 

  /* Some operations on arr[] */
  arr[0] = 10; 
  arr[1] = 20; 

  return arr; 
} 

int main() 
{ 
  int* ptr = fun(); 
  cout << ptr[0] << " " << ptr[1]; 
  return 0; 
} 

Output:

10 20

Using static array:

Lifetime of a static variable is throughout the program. So we can always create a local static array and return it.

#include <iostream> 
using namespace std; 

int* fun() 
{ 
  static int arr[100]; 

  /* Some operations on arr[] */
  arr[0] = 10; 
  arr[1] = 20; 

  return arr; 
} 

int main() 
{ 
  int* ptr = fun(); 
  cout << ptr[0] << " " << ptr[1]; 
  return 0; 
} 

Output:

10 20

Using struct:

We can wrap array in a structure/class and return an instance of the struct/class. The reason for this work is, array members of structures are deeply copied. In below program deep copy happens when we returned instance is copied in main.

#include <iostream> 
using namespace std; 

struct arrWrap { 
  int arr[100]; 
}; 

struct arrWrap fun() 
{ 
  struct arrWrap x; 

  x.arr[0] = 10; 
  x.arr[1] = 20; 

  return x; 
} 

int main() 
{ 
  struct arrWrap x = fun(); 
  cout << x.arr[0] << " " << x.arr[1]; 
  return 0; 
} 

Output:

10 20

 

Leave a Reply

Your email address will not be published. Required fields are marked *