Arrays

Array is a data type which is used to store multiple values of same data type in a single variable.

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.

Accessing Elements of Array

We can use indexes to access elements of array.

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.

Taking input in arrays

We can take input in arrays with the help of cin object and extraction in the same way we take input in out int or other variables. We can manually take input in arrays at specified indexes or we can use loop to take input in arrays.

Changing elements of array

We can change the elements of array at any index we 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 4 bytes 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]);