We will discuss some properties of array in C++. After that, we will learn to initialize arrays in C++ language and how to access and use them with the help of examples.
In the end, we will learn to implement and perform basic operations on arrays. Before moving on to the topic let us discuss what arrays are.
What are Arrays?
Before we start, let us first discuss what variables are. Variable is the name given to a memory location where we want to store our values or data of any datatype.
For Example,
#include <iostream>
using namespace std;
int main() {
int num;
boolean myBool;
char let;
String word;
return 0;
}
Here ‘num’, ‘myBool’, ‘let’, and ‘word’ are called variables. Suppose we want to store more than one value or data of the same datatype. We have to create multiple variables of that datatype. It creates redundancy in our code. So to store multiple data of the same datatype in one variable only, we use arrays.
An array is a data structure that stores multiple data of the same datatype in a contiguous block of memory.
Properties of Arrays in C++
Now, let us see some properties of arrays in C++.
1. Arrays are Homogeneous
Arrays are collections of similar data that can contain any data collection of similar datatype only. Also, arrays can store data of derived datatype like structures, pointers, etc.
2. Arrays store data in contiguous memory locations.
If we have an array of integers of size 10, then the addresses will be consecutive.
1000
1004
1008
1012
1016
1020
1024
1028
1032
1036
Here, every memory location differs by four because the integer has a size of 4 bytes. This goes the same with all other datatypes. For example, char, the addresses will differ by 1 byte.
3. Size of an array is fixed and has to be mentioned while declaring.
One of the disadvantages of arrays is that it has fixed size, and the user has to mention it while declaring. The size of the array cannot be changed further as per the user's requirement.
4. The indexing of elements of an array starts from zero.
We have an array of length n; then the first element is indexed zero, the second element is indexed 1, the third is indexed 2, and so on. And the last element is indexed (n-1). For example, below is the array of seven integers.
5. Arrays can be multi-dimensional.
Multi-dimensional arrays can be termed as an array of arrays that contains homogeneous data in tabular form.
C++ Array Types
Arrays in C++ can be of two types:-
1. One-Dimensional
One-dimensional arrays in C++ are collections of elements of the same data type arranged in a linear sequence. They are also known as flat arrays.
You can declare a one-dimensional array using the following syntax:-
Syntax
datatype arrayName[arraySize];
Example:
#include <iostream>
using namespace std;
int main() {
int nums[3];
nums[0] = 10;
nums[1] = 20;
nums[2] = 30;
for (int i = 0; i < 3; ++i) {
cout<<nums[i]<<" ";
}
return 0;
}
You can also try this code with Online C++ Compiler
When you initialize a 2D array, you must always specify the second dimension(no. of cols), but providing the first dimension(no. of rows) may be omitted.
Example:
#include <iostream>
using namespace std;
int main() {
int nums[][2] = {{1, 2}, {3, 4}};
for (int i = 0; i < 2; ++i) {
for(int j = 0; j < 2; ++j){
cout<<nums[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
You can also try this code with Online C++ Compiler
This code performs linear search on a one-dimensional array, if the target is found, the index is printed. Each element of the array is accessed using its index.
Output:
10 20 30
Arrays support O(1) access if you know the index of an element.
C++ Array Initialization
There are various ways to declare arrays in C++. Arrays in C++ can be declared and initialized at the same time.
1. Declaring an array of size five
Syntax- datatype arrayName[ Size of the array ] ;
int arr[ 5 ] ;
2. Declaring and initializing each element
int arr[ 5 ] = { 1, 2, 3, 4, 5 } ;
3. Declaring and initializing only the first element
int arr[ 5 ] = { 1 } ;
4. Declaring and initializing every element by 0.
int arr[ 5 ] = { } ;
Accessing array elements - In the above examples, each array is named 'arr.' We can access any element of an array by its index.
Here, we can access each element of the array by its index.
Output
Performing and Implementing Arrays Operations in C++
Till now we have learned to declare and initialize the arrays. We also know how to access array elements using their indexes. Now we will perform some basic operations on arrays in C++, to become familiar with arrays.
1. Taking input array from users and printing the array elements
#include <iostream>
using namespace std;
int main()
{
// Size of the array to be made
int n;
cout << "Enter the size of the array: " << endl;
cin >> n;
// Declaring an array of size n;
int values[n];
cout << "Enter " << n << " integers: " << endl;
// Take array elements as input from the user
for (int i = 0; i < n; ++i)
{
cin >> values[i];
}
cout << "The integers are: ";
// Print array elements
for (int i = 0; i < n; ++i)
{
cout << values[i] << " ";
}
return 0;
}
You can also try this code with Online C++ Compiler
The array size and array elements are taken from the user.
Let us suppose the input array is of size five, and the elements are as follows: 8 1 5 6 3.
Then the output will be:
Output
2. Calculating the sum and average of all the elements of an array.
#include <iostream>
using namespace std;
int main()
{
// Declaring an array
int nums[10] = { 5, 6, 7, 8, 4, 1, 3, 2, 4, 9 };
double sum = 0;
double avg = 0;
// Printing array elements
for (int i = 0; i < 10; ++i)
{
cout << nums[i] << " ";
}
// Adding all the elements of the array to calculate the sum
for (int i = 0; i < 10; i++)
{
sum += nums[i];
}
// Calculating the average
avg = sum / 10;
cout << endl << "Sum = " << sum;
cout << endl << "Average = " << avg;
return 0;
}
You can also try this code with Online C++ Compiler
Here, the sum is calculated, and the average is displayed.
Advantages of Array in C++
Following are the advantages of arrays in C++:-
Easy and Efficient Access: Arrays store the elements in contiguous memory locations which makes traversing and modifying the array fast and efficient.
Simple Syntax: The syntax for working with arrays in C++ is straightforward and easy to understand. Arrays provide a simple and intuitive way to organize and manipulate data, making them suitable for various programming tasks. In C++ the syntax used for declaring, accessing and modifying arrays is very simple and easy to understand.
Flexibility: In C++, you can easily create arrays of built-in data types such as int, string, float, etc., or for the objects of user define classes.
Compatibility with C: C++ arrays are compatible with C-style arrays which allows you to easily work with existing C code or libraries.
Static Memory Allocation: In C++, arrays are allocated memory statically, which means their size is determined at compilation. It can be useful when size requirement is already know, so that you can avoid using dynamically allocated vectors.
Disadvantages of C++ Array
Following are the disadvantages of arrays in C++:-
Dangling pointers: Pointers that point to memory locations that have been deallocated are referred to as dangling pointers. If an array is destroyed without first nullifying the pointer to it, this may occur. Programme crashes and memory damage can result from dangling pointers.
Memory leaks: It happen when no longer required memory is returned to the operating system. If an array is not correctly deallocated, this may occur. Programme memory exhaustion may eventually result from memory leaks.
Buffer overflows: A buffer overflow occurs when data is written to a buffer in excess of the space allotted for it. If an array is too small or the subscript operator is used improperly, this can occur.
Frequently Asked Questions
What is an array in C++?
In C++, an array is a data structure that stores elements of the same data type in a contiguous block of memory. In C++, arrays are 0-base indexed and they support random access.
What is an array with example?
An array is a data structure that stores elements in a contiguous block of memory. A real life example of an array is a grocery list, each item on the list is an element and the list as a whole is an array.
What are the 3 types of arrays?
Three array types are 1D (linear), 2D (tabular), and multidimensional (with more than two dimensions) for structured data storage.
What is array and its types?
An array is a data structure for storing elements of the same type. Types include 1D (linear), 2D (tabular), and multidimensional (complex structures).
Conclusion
In this blog, we have learned how to use arrays in C++. We understood the basic need for arrays and saw the methods to declare and access them. We also did some basic operations on arrays in C++.