Arrays

Arrays are data type in C++ which are used to store multiple values of same data type.

Why we need Arrays?

In C++, if you want to store marks of ten students, you will have to declare ten variables. But if you use arrays, you do not have to declare ten variables. As data type of all these variables is same, you can use only one array to store them.

Here size stores, how many elements are there in array and if you want to access data on some individual at any index, you can access,

Accessing Elements of Arrays

We can access individual elements of arrays using indexes. name[0] will access first element of array.

Similarly name[2] will access data at index 2 and it will be on third number because index starts from zero.

Problem

It is easy to print when size of array is 10, 20, 30 or 100. But imagine if the size of array is 1 million, is it good to print individual indexes like this? What we are doing here? We are doing the same work over and over again. And we have seen that when we need to repeat our same block of code, we use loops.

Solution

Taking input in arrays

Changing elements of array

You can change the elements of array at any index you want.

Note: If you do not specify the size of array, it is ok.

Note: Point: If we do not know the size, to which number we will run loop?

Find size of array

sizeof() operator as discussed earlier will give you the size of array. Size of array does not gives you the number of elements in array. As size of int is 4bytes and we have three integers, so size of array will be 12 bytes. For this purpose, we have to divide size of array with size of datatype.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Array indexing starts from which number?

10 XP~2 min
Exercise 2 of 2Easy

What will be printed?

15 XP~3 min
int arr[] = {10, 20, 30};
printf("%d", arr[1]);