Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

ARRAYS IN C++

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 at runtime.

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.
2. Arrays store data in contiguous memory locations.
If we have an array of integers of size 8, then the addresses will be consecutive.
1000 1004 1008 1012 1016 1020 1024 1028

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

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][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:
12
34

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.

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.

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

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

Run Code

Output

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.

You might also like