Arrays in C++ | Topic 14 | VU Insider

The Scenario

Suppose you have to calculate the average age of 10 students. At first, you will declare 10 variables to store different ages of each student. Then you will add all 10 ages and divide it to 10 to get the average age.

Now suppose you have to calculate the average age of 100 students. In this case, we have to declare 100 variables i.e one for each student.

How to deal with that kind of problems?

Arrays are the solution.

Arrays in C++

Array is a special data-type. If we have collection of data with same type then arrays can be useful. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

data-type array-name[size];code-box


Array of integers:
int ages[4];

// To create an array with 4 integers:
int ages[4] = {18, 21, 31, 23};code-box

Array of strings:
string books[4];

// To create an array with 4 strings:
string books[4] = {"English", "Maths", "Science", "Islamiyat"};code-box

Take a look at picture

You can see 10 memory cells. The number in [ ] is the index index of array. C[0] is used to store 1st value, C[1] for 2nd and so on.

It should be clear that when we call index 6 ( C[6] ) in an array, it means we are calling 7th element of array. To better understand it, let's take a look at example.

string books[4] = {"English", "Maths", "Science", "Islamiyat"};
cout << books[0];
// The output will be "English".

string books[4] = {"English", "Maths", "Science", "Islamiyat"}; cout << books[2];
// The output will be "Science".code-box

Can I change specific Array element?

Yes you can change the specific element of an array by referring its index number.

string books[4] = {"English", "Maths", "Science", "Islamiyat"};

books[0] = "Biology"; // changes "English" to "Biology"
cout << books[0];code-box

Output will be "Biology" instead of "English".

Array Loops in C++

You can loop through the array elements with "For" loop. The following example prints out all elements in the "books" array.

string books[4] = {"English", "Maths", "Science", "Islamiyat"};
for(int i = 0; i < 4; i++) {
cout << books[i] << "\n";

Array Size

Let's say you have to make a program that will store information of new students who will get admission in upcoming fall. Here you don't know the exact number of students. A problem will be created if number of students get bigger then array size you declared. Or you can specify extra space for array if number of students get smaller then array size.

string books[5] = {"English", "Maths", "Science"};

// Size of array is 5, even though it's only three elements inside it. Memory got wasted!code-box

How to overcome this problem?

Solution: Simply, you just don't have to specify the size of the array. If you don't, it will only be as big as the elements that are inserted into it.

string books[] = {"English", "Maths", "Science"};code-box

Post a Comment

Previous Post Next Post