Lecture - Two - Arrays & For Loop
Lecture - Two - Arrays & For Loop
ARRAYS
Declaration of Arrays
To declare an array, specify the data type, the array name, and the size of the array in
square brackets
dataType arrayName[arraySize];
int numbers[5];
Example 02: strings
string cars[4];
ARRAYS
C++ Array Initialization
In C++, it’s possible to initialize an array during declaration
To insert values to it, we can use an array literal - place the values in a comma-separated
list, inside curly braces:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of three integers, you could write
int myNum[3] = {10, 20, 30};
If you initialize only a subset of elements, the remaining elements are initialized to 0 by
default:
int numbers[5] = {1, 2, 3}; // numbers will be {1, 2, 3, 0, 0}
ARRAYS
Access the Elements of an Array
We can nd out the total number of elements in the array simply by multiplying its
dimensions:
i. e 2 x 4 x 3 = 24
fl
fi
ARRAYS
Multidimensional Array Initialization
Like a normal array, we can initialize a multidimensional array in more than one way.
Initialization of two-dimensional array
int test[2][3] = {2, 4, 5, 9, 0, 19};
The above method is not preferred. A better way to initialize this array with the same
array elements is given below:
int test[2][3] = { {2, 4, 5}, {9, 0, 19}};
ARRAYS
Multidimensional Array Initialization
This array has 2 rows and 3 columns, which is why we have two rows of elements with 3
elements each
ARRAYS
Multidimensional Array Initialization
fi
FOR LOOP
Explanation
Initialization: int i = 0 sets the starting point.
Condition: i < 5 checks if the loop should continue.
Update: i++ increases the value of after each iteration
i
int main() {
int numbers[] = {10, 20, 30, 40, 50};