Table of Contents


Arrays

Problem

What Is Array ?

Array Declaration & Accessing

// DataType + name [size];
int arr[5]; // holds 5 ints
char charArr[100]; // holds 100 chars

// Accessing elements (0-based indexing [0 , size - 1])
arr[0] = 10;
arr[1] = 15;
cout << arr[0];

Array Initialization

Initially any array holds garbage values (unpredictable value that a variable may contain when you use it without initializing it.)

int x[5];
cout << x[1]; // Undefined behavior

You have different ways to initialize the array :

int a[]{1 , 2 , 3 , 4}; // same as int a[] = {1 , 2 , 3 , 4};
int b[4]{}; // all elements ==> 0
int c[5]{1 , 2}; // initialize only the first two elements and the rest is zero

Note : Don’t try to initialize array with non-const variable size because it’s compile error

(SEARCH FOR MORE INFORMATION!!!!!)

Array Traversing

You can traverse arrays in specific manner using loops :