Arrays are the key component of C++ programming, widely used in almost all aspects of development. C++ is a popular language, and arrays are an essential part of it. In this article, we will take a closer look at C++ arrays and explain their various features in detail.
C++ Arrays
An array is a collection of variables of the same type, all having a single, collective name. It consists of a series of consecutive memory locations, each referred to as an element, and has a predetermined length indicating the number of such elements included. Arrays are a powerful data structure, allowing for convenient storage and manipulation of multiple values of the same type.
Arrays are an efficient way of storing and managing large datasets. For example, if you need to store the marks of 100
students, it would be tedious and inefficient to declare 100
individual variables. Instead, you could use an array to store the data, allowing for easy access, retrieval, and manipulation of the data. Arrays also provide an effective way to store and organize similar kinds of data, making them an invaluable tool for data management.
Syntax Of C++ Array
The following is the general syntax of an Array in C++.
Data_Type Array_Name [Size_Of_Array];
For example,
int marks [100];
Here, 'marks'
is the array name, and the number within the brackets [100]
indicates the size of the array. This array will store 100
integer values (in this case, marks).
Representation Of Array in C++
Elements of an array are stored sequentially in computer memory, with each element occupying a consecutive set of memory locations.
Consider an Array X
that contains 6
integers values of type int. It can be represented as:
For example if in the above array X we store the marks of 6 students and inside the computer memory, the first element X[0] is stored at address 100
, then X[1], X[2], X[3], X[4], X[5]
will be stored at memory addresses 100, 102, 104, 106, 108,
and 110
respectively. Here the difference in the values of the memory addresses is two numbers because an int data type occupies 2 bytes of memory space.
In the above example, the numbers 12, 04, 19, 67, 41, and 34 are called Data items.
X
is the name of the array. It can be any valid identifier. Each location of the array has the same name with a different index. In the above example, all 6 locations of the array X
have the same name, X
but different indices.
The numbers 0 to 5 are called the Index of each element. The index is the location number of that element.
The numbers 100, 102, 104, 106, 108, and 110 are called memory addresses.
Array Index Always Starts From 0, But Why?
The answer to this question is rooted in the history of computer science. Array indices in programming languages are typically zero-based, meaning they start counting from 0
. This is because most programming languages are based on the C programming language, which in turn is based on the B programming language. B was a language developed in the 1970s by Ken Thompson and Dennis Ritchie at Bell Labs, and it was the first language to adopt zero-based array indexing.
Thompson and Ritchie chose to start counting from 0
because it made certain programming operations, such as pointer arithmetic, simpler and more efficient. Therefore, the practice of using zero-based array indices has been passed down through the generations of programming languages and is now the de facto standard.
Size Of The Array:
Size of the array is a term used to describe the total number of elements within an array. It is also sometimes referred to as the length of the array.
For example,
int M[10];
In the above example, the size of the array M
is 10
, which means that we can store only 10
integer values in this array.
Array Initialization in C++
Array initialization is the process of assigning values to array elements at the time of array declaration. This process provides an initial list of values for the array elements.
When initializing an array, keep in mind the following:
- The values of an array must be separated by commas and enclosed within braces {}.
- At least one initial value must be included within these braces.
- if more values are given than the array has space for, a syntax error will occur.
- If the number of initial values is less than the array size, the remaining elements will be initialized to zero.
Syntax Of Array Initialization In C++
The following is the general syntax of Array Initialization:
Data_Type Identifier[Length/Size] = {List_Of_Values};
- Data_Type: It indicates what type of data of the values to be stored in the array. It could be either int, float, or any other type.
- Identifier: It is a name that is given to each array. It indicates the name of the array.
- Length/Size: It indicates the total number of elements in the array.
- List Of Value: It indicates the values to initialize the array, and these values must be constant.
For example,
int marks[8] = {82, 79, 90, 47, 61, 74, 39, 51};
In the above example, an integer array marks
with 8 elements has been declared. It also initializes the array with values given in the braces { }
. In the above example, marks [0]
are initialized to 82
, marks[1]
to 79, and so on.
Example 1: A Simple Example Demonstrating The Concept Of Arrays in C++
#include <iostream> using namespace std; int main() { int array[5]={10,20,30,40,50}; //Declaring an array with 5 elements cout<<"Displaying the elements of the array: "<<endl; for (int i=0; i<5; i++){ //Looping through each element cout<<"Element at index "<<i<<" is "<<array[i]<<endl; } cout<<endl<<endl; cout<<"Adding 10 to each element of the array"<<endl; for (int i=0; i<5; i++){ array[i] +=10; //Adding 10 to each element } cout<<endl; cout<<"Displaying the elements of the array after adding 10:"<<endl; for (int i=0; i<5; i++){ cout<<"Element at index "<<i<<" is "<<array[i]<<endl; } return 0; }
OUTPUT:
Displaying the elements of the array:
Element at index 0 is 10
Element at index 1 is 20
Element at index 2 is 30
Element at index 3 is 40
Element at index 4 is 50
Adding 10 to each element of the array
Displaying the elements of the array after adding 10:
Element at index 0 is 20
Element at index 1 is 30
Element at index 2 is 40
Element at index 3 is 50
Element at index 4 is 60
1. The first step is to declare an array of size 5 with the elements 10, 20, 30, 40, and 50. This is done using the code:
int array[5]={10,20,30,40,50};
2. The next step is to use a for loop to display the elements of the array. This is done using the following code:
for (int i=0; i<5; i++){
cout<<"Element at index "<<i<<" is "<<array[i]<<endl;
}
3. The third step is to use another for loop to display the elements of the array after adding 10. This is done using the code:
for (int i=0; i<5; i++){
cout<<"Element at index "<<i<<" is "<<array[i]<<endl;
}
4. The last step is to return 0, indicating that the program was executed successfully. This is done using the code:
return 0;
Example 2: A C++ Program That Will Take Input From The User and Store Them in an Array
#include<iostream> using namespace std; int main() { int n; cout<<"Enter a number: "; cin>>n; int arr[n]; cout<<endl; cout<<"Enter "<<n<<" Numbers:" <<endl; for(int i=0; i<n; i++) { cin>>arr[i]; } cout<<endl; cout<<"The numbers you entered are: "; for(int i=0; i<n; i++) { cout<<arr[i]<<" "; } return 0; }
OUTPUT:
Enter a number: 4
Enter 4 Numbers:
5
6
2
1
The numbers you entered are: 5 6 2 1
The above program is used to take input of n numbers from the user and store them in an array. The program starts by asking the user to input a number to define the size of the array. Then the program uses a for loop to take input of the n numbers and store them in the array. Finally, another for loop is used to print the numbers stored in the array.
Example 3: A C++ Program That Will Display The Sum, Product, Average, and Difference of Array Elements
#include <iostream> using namespace std; int main() { int array[100], sum = 0, product = 1, difference; float average; cout << "Enter The Size Of The Array: "; cin>>array[100]; cout << "Enter "<< array[100] << " Numbers For Calculations:"<<endl; // Taking input from user for (int i = 0; i < array[100]; ++i) { cin >> array[i]; } // Calculating the sum of elements present in array. for (int i = 0; i < array[100]; ++i) { sum += array[i]; } // Calculating the product of elements present in array. for (int i = 0; i < array[100]; ++i) { product *= array[i]; } // Calculating the average of elements present in array. average = (float)sum / array[100]; // Calculating the difference of elements present in array. difference = array[array[100] -1] - array[0]; // Displaying the output cout<<endl<<endl; cout << "Sum of array elements: " << sum << endl; cout << "Product of array elements: " << product << endl; cout << "Average of array elements: " << average << endl; cout << "Difference of array elements: " << difference << endl; return 0; }
OUTPUT:
Enter The Size Of The Array: 5
Enter 5 Numbers For Calculations:
4
7
3
9
2
Sum of array elements: 25
Product of array elements: 1512
Average of array elements: 5
Difference of array elements: -2
The above program will perform different types of calculations on an array. It initializes an array with 5 elements. It then calculates the sum, product, average, division, and difference of the array elements. Finally, it displays the output of the calculations.
Array Out Of Bound:
An array out of bounds occurs when you try to access an element outside the bounds of the array. This can happen either when trying to access elements before the start of the array or after the end of the array.
Example:
int arr[5] = {10, 20, 30, 40, 50};
// Accessing an element before the start of the array
std::cout << "arr[-1] = " << arr[-1] << std::endl;
// Accessing an element after the end of the array
std::cout << "arr[5] = " << arr[5] << std::endl;
This code will cause an array out-of-bounds error since we are trying to access elements outside the bounds of the array.