'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Oct 15, 2023
Easy

Array in C++

Author Vikash Kumar
1 upvote
gp-icon
Basics of C++
Free guided path
9 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

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. 

array in c++

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 areVariable 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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.

array

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;
}

 

This code declares an array of integers, traverses over this array using a for loop and prints the elements.

Output:

10 20 30

2. Multi-Dimensional

Multi-dimensional arrays in C++ are used for representing data organized in multiple dimensions such as matrices.

You can declare a multi-dimensional array using the following syntax:-

Syntax

datatype arrayName[dimension1Size][dimension2Size];


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;
}

 

This code declares a 2x2 matrix, traverses over it using 2 nested for loops and prints the elements.

Output:

1 2
3 4

C++ Array Declaration

In C++, an array is declared as follows:

data_type array_name[size] 

 

Where size is the number of elements in the array, array_name is the array's name, and data_type indicates the type of the array's elements.
 

Access Elements in C++ Array

You can access elements in a C++ array using their respective indices.

You can use the following syntax to access in element in an array using its index:-

Syntax

arrayName[elementIndex]

 

The following code accesses the elements of a C++ array:-

Example:

#include <iostream>
using namespace std;
int main() {
    int nums[5] = {3, 2, 1, 5, 7};

    int idx = -1, target = 1;

    for (int i = 0; i < sizeof(nums)/4; ++i) {
        if(nums[i]==target){ /* access element */
            idx = i;
            break; /* element found, terminate search */
        }
    }

    if(idx!=-1){
        cout<<"Target found at index: "<<idx;
    } 
   
   return 0;
}

 

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 ] ; 
Declaring an array

 

2. Declaring and initializing each element

int arr[ 5 ] = { 1, 2, 3, 4, 5 } ;        
initializing each element

 

3. Declaring and initializing only the first element

int arr[ 5 ] = { 1 } ;                          
initializing only the first element

4. Declaring and initializing every element by 0.

int arr[ 5 ] = {  } ;                          
initializing every element by 0

Accessing array elements - In the above examples, each array is named 'arr.' We can access any element of an array by its index.

For example- 

#include <iostream>
using namespace std;

int main(){
	int arr[6] = { 5, 6, 2, 3, 9, 1 };
	cout << arr[0] << endl;
	cout << arr[1] << endl;
	cout << arr[2] << endl;
	cout << arr[3] << endl;
	cout << arr[4] << endl;
	return 0;
}

Here, we can access each element of the array by its index. 

Output

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;

}

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

printing the array elements

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;

}

 

Output

elements of an array

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++.

Check out other related articles to learn more: 

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

Previous article
Introduction to Array
Next article
Single-Dimensional Arrays
Guided path
Free
gridgp-icon
Basics of C++
9 chapters
104+ Problems
gp-badge
Earn badges and level up
Live masterclass