Arrays in C++
Before introducing arrays, let me take up a simple question. Suppose there are 3 students: Riya, Jubin and Kirti. We need to write a program to input their marks and print their average.
I'd probably create 3 variables, take input, and print the average.
Something like this!
#include<bits/stdc++.h>
using namespace std;
int main()
{
int marks1, marks2, marks3;
cin >> marks1 >> marks2 >> marks3;
double avg = (marks1 + marks2 + marks3)/3.0;
cout << avg << '\n';
return 0;
}
Now think about taking average of the marks of 100 students. It would be quite a hassle if we had to create separate variables for each person's marks, right? That's where arrays come in handy.
Introduction
An array is like a list of items, but each has a specific place. It's similar to lining up a bunch of boxes in a row. You can put things in these boxes (items) and easily find a specific box by knowing its position in the row (index). This helps you organize and work with lots of items efficiently.
In the first example, imagine an array like a storage box that can hold many items. In our case, it's like a row of 100 boxes that can store the marks of all 100 students in one go.
Instead of dealing with hundreds of individual variables, we use a single array to keep things organized.
Now that you have a basic idea of why arrays are important, let's learn about it in detail.
Key points
- Organized Storage: In programming, a single data type like int is used to store one piece of integer data. An array, on the other hand, is a collection of elements that are all of the same type. This implies that if you have an array of int, you can store multiple integers together in this structured way. Hence, arrays in C++ provide a way to organize and store similar elements together.
- Data type of elements: In C++, a single array can hold elements of the same data type only. For example: an int array should only store elements that are all of int data type.
Exception: There are a few languages (like Python) where elements of a single array can be of different data types.
Array1 = {1, 2, 3, 4, 5}
Array2 = {1.8, 5.2, 3.1, 4.2, 2.44}
Array3 = {2, 600, 2.5, h, 3.333}
/* Here, Array1 and Array2 can be created in C++ as they both contain
all elements with same data type (Array1 with int & Array2 with double)
but Array3 will throw error in C++ as data type of all the elements
isn't the same */
/* Languages like Python supports all types of array
and hence all 3 arrays given above can be easily created there*/
- Contiguous Memory: When you declare an array, the system allocates a block of memory where each element of the array is stored right next to the other, in a continuous sequence. This is what we mean by "contiguous" memory. No gaps or interruptions exist between the elements, ensuring efficient access.
Consider an integer array as int arr[5];
Assuming int
is 4 bytes (which is common in many environments, though the actual size can depend on the compiler and architecture), this array will require 16 bytes of contiguous memory (4 elements * 4 bytes per element).
Note: We'll be diving deeper into the concept of memory allocation in the upcoming articles.
- Index-Based: C++ arrays are index-based. The first element is at index 0, the second at index 1, and so on. This indexing is known as 0-based indexing.
- Efficiency: Arrays in C++ are efficient for random access and manipulation of elements. Because of contiguous memory allocation, it's easy to find the address of any element.
Disadvantages
- Fixed Size: C++ arrays have a fixed size, and you need to know the size at compile time. Hence, it's not feasible to change the size of the array, once created. Sure, you can create a new array of the desired size and copy the elements, but resizing the existing array isn't possible.
- No Dynamic Resizing: Arrays do not automatically resize during runtime.
In case you are thinking about vectors and its working then don't worry, we'll take that up in detail later 😉
Create an Array
Declaring
The following code explains one of the ways to declare an array in C++:
// The skeleton:
// data-type array-name[array-size];
// Examples:
int marks[5];
char grade[5];
string name[20], address[20];
// Example for variable sized array:
int n; cin >> n;
int arr[n];
When we declare an array inside a function and don't initialise it with anything, the values at different indices are random for many data types (e.g. int, double, char etc.) and empty for a few others (e.g. string). The random values are termed garbage values.
Note: In C++, it's not feasible to change the size of the array, once created. Sure, you can create a new array of desired size and copy the elements, but resizing the existing array isn't possible.
Initializing
In a normal way, the following is the way to do it where you enclose the values in {}. Eg.
int arr[5] = {1, 2, 3, 4, 5};
What if you enter fewer values than the array_size in {}?
int arr[5] = {1, 2, 3};
int arr[5] = {};
In the cases above, the elements aren't assigned garbage values; the values are 0. This implies that the arrays would be {1, 2, 3, 0, 0} & {0, 0, 0, 0, 0} respectively.
What-ifs!
Now let's see some 'what-if' cases in arrays.
What if we don't provide array size while creating an array?
If we declare an array like arr[];
then it will throw a compilation error but if we provide array
elements while creating an array, we can omit the array size. Something like
this:
int arr[] = {1, 2, 3, 4, 5};
Here, the size of arr would be
automatically defined as 5.
Size of an array 'arr' in C++ can be
calculated as:
int size = sizeof(arr) / sizeof(arr[0]);
What if no. of elements is less than the size during array initialization?
int arr[5] = {1, 2, 3};
int arr[5] = {};
In the above cases, values of remaining/
undefined elements would be 0 by default.
So, the first array would be: {1,2,3,0,0}
and second array would be: {0,0,0,0,0}.
What if I enter more values inside {} than the corresponding size?
I'll get a compilation error : (
What if I enter a character in an integer array?
I'll get a compilation error : (
What if I declare an array first int arr[3]; and then initialise it later on: arr = {1, 2, 3}?
I'll get a compilation error : (
The array was already initialized during the time of declaration and the elements were assigned the default value of 0. Hence, re-initialization throws an error and we need to manually re-assign values to all the array elements.
Access array elements
If we create an array of size N, then the positions of the elements in the array are 0, 1, 2, and so on ... N-1. The positions are called "indices" (singular being "index"). In other words:
- The 1st element is present at index 0.
- The 2nd element is present at index 1.
- ... The pattern goes on ...
- The (N-1)th element at index N-2.
- Finally, the Nth element at index N-1.
Imagine we have an integer array arr of size 7. A visual representation of arrays and their indices would be:
How to access the value at index i?
The way to access the ith element of an array having the name arr is arr[i] (where [] is called the subscript operator). Let me explain this using different use cases.
Imagine we have an integer array arr of size 10.
Taking input of all elements:
for(int i = 0; i < 10; ++i) {
cin >> arr[i];
}
Printing elements:
// Let's say we want to divide the elements by 2 until they're even,
// and then print the odd leftover.
for(int i = 0; i < 10; ++i) {
while(!(arr[i]%2))
arr[i] /= 2;
cout << arr[i] << ' ';
}
FAQs
What other things can I do with arr[i]?
Let's say arr is an integer array. You can treat arr[i] as if it were an integer variable only.
What if someone tries to access a negative index? (eg. arr[-1])?
It's not a very uncommon mistake and has personally happened to me as well. In such a case, you don't get a compilation error; the behaviour is undefined at runtime. It could:
- Either lead to a runtime error.
- Or the value could be a random garbage value.
What about an index >= N for an array of size N?
Again, the answer is same as if someone tries to access a negative index.
What happens if I print arr only?
Good Question! Try it. It'll print the memory location address where the array is stored. (in hexadecimal)
Quiz
Example
Problem statement: Create the array {1, 2, 3, 4, 5}
, initialize it, and print its elements.
Code:
#include <iostream>
using namespace std;
int main() {
// create an array named arr of size 5
int arr[5] = {1, 2, 3, 4, 5};
// access first element
cout << arr[0] << endl;
// access second element
cout << arr[1] << endl;
// access third element
cout << arr[2] << endl;
// access fourth element
cout << arr[3] << endl;
// access fifth element
cout << arr[4];
return 0;
}
Output:
1
2
3
4
5
Here, observe how we create the array and access its elements.
With this, we come to the end of this article. I hope you got an idea about what arrays are and how can we create them. There's a lot more about them that we will be learning in the upcoming articles. So stay tuned : )