Arrays in C++

Arrays in C++

Hi, Guys welcome back to our next article in the C++ basic module, which is very important from a programming point of view i.e. Arrays in C++. Please read our previous article where we discussed Loops in C++. At the end of this article, you will understand the following pointers in detail.

  1. What is an array?
  2. Why do we need an Array?
  3. Declaring an and Initialization of an Array
  4. Advantages and Disadvantages of Arrays in C++
  5. What is an Array Index?
  6. Different types of Array?
  7. The relation between Array and loops
What is an Array?

An array is a kind of sequential data structure, which is used to store the collection of items of the same type.

Note: I am sure you didn’t get this definition of an array. Let’s discuss the above statement in layman terms rather than programming terms.

We already learned that variables are used to store the value. But variable can hold only one value of a specific type at a time. For a better understanding please have a look at the below diagram. In the below example at any point in time x can hold only one type of value.

What is an Array?

Now in real-time programming, there will be a scenario where we need to store a group of values. You didn’t get it, right? Yeah, let’s think in this way. I want to store emp no of 10 employees. Then without an array, it is like

int employeeno1=1;
int employeeno2=2;
int employeeno3=3;
…………………………
………………………..
int employeeno10=10;

I know you already feel this awkward. Yes, if the array kind of data structure is not there then programming would be a bit more complex. For everything we need to define a new variable even if it is of the same type. But let’s see how the array solves this problem.

int employeeno[10]={1,2,3,4,5,6,7,8,9,10};

How using [] this work in real memory?

Int empno[5]={1,2,3,4,5};

Why do we need an Array?

See using this [] along with the variable name you are informing the compiler that the variable is an array and allocate a block of memory as specified by the array in memory.

Note: Normal array is stored in stack however it is possible to create an array in heap memory also which will be discussed in future articles on dynamic memory allocation.

Declaring and Initializing an Array in C++

We have discussed the importance of an array over normal variables but now let’s discuss what are the ways to declare and initialize an array with examples.

General Syntax:
<data type> variablename[size of the array];

Example:
int array[5];

Array declaration by specifying the size in C++

The following is an example of an array declaration by specifying the size.
int n=10;
int array[n];

Declare and initialize an array in the same instruction

Just like declaring and initializing the normal variable in a single instruction, we can also follow the same for array if we want to hardcode the input of the array;

Examples:
int array[]={1,2,3,4,5}
int array[5]={1,2,3,4,5}

Advantages of Arrays in C++:
  1. We can access any element in an array using the array index.
  2. Sorting in an array is easy
  3. Easily we can access all the elements through the traversal in a single loop
Disadvantages of Arrays in C++:
  1. Array in C++ is fixed size and we need to define the size of an array while declaration.
  2. Insertion and deletion of an array could be a costly operation.

Note: To know more about time complexity and more insight into an array as a data structure please refer to the Data Structure and Algorithm course by DotNetTutorials.

Student: Author you said accessing all the elements in an array is easy and it is through the index but I am not getting how to do it?

Author: Yes, don’t be in a hurry our next discussion is all about what is an index of an array? And also, how to access all the elements in an Array.

Let us directly get into the details of it.

What is an Array Index?

If I directly explain the concept of array index you might be in some confusion. So, let’s take an example:

int temp[5]; Here temp variable name stores the address of the first element of an array.

What is an Array Index?

In the above example to access all the elements in an array, we need the address of temp[0] and that address is stored in the temp variable. So, the array name gives the address of the first element in an array. Since I know the address of the first element of an array it is easy to access the second element in an array through an index of an array.

Now let’s get to what is an index of an array?

The index of an array is basically a pointer that is used to indicate which element in the array will be used. The array is sequential starting at zero to n-1 you can easily access any element in a small array with the index.

Example: int empno[5]={1,2,3,4,5};

what is an index of an array?

In the above example to print the value 4 if I just use the below instruction is enough.

cout<<empno[3];

Note: Array index is an integer starting from 0. And zero index will always be given by the name of the array.

Program to check the above example:
#include <iostream>
using namespace std;
int main() {
 int empno[5]={1,2,3,4,5};
 cout<<"to print value 1\t"<<empno[0]<<endl;
 cout<<"to print value 2\t"<<empno[1]<<endl;
 cout<<"to print value 3\t"<<empno[2]<<endl;
 cout<<"to print value 4\t"<<empno[3]<<endl;
 cout<<"to print value 5\t"<<empno[4]<<endl;
 return 0;
}

Output:

Arrays in C++ with Examples

In the above program, you came to know that using array index we can get the value associated with that index but the program looks awkward when I try to print all the elements in an array.

Yes, you’re right I have used five cout statements to print the five elements of an array. This looks similar to declaring five new variables and initializing it and print them separately. To avoid multiple cout and also to read multiple inputs from the user for an array we need to use counter loops. Yes, you guessed it right counter loops are nothing but for loop and for each loop.

The relation between counter loops and Array in C++.

Since we know the first index of an array from the array name and also, we know array is contiguous and hence index is also contiguous from 0 to size of an array-1. We can make use of Counter loops for traversal purposes. Let’s modify the above example:

Int empno[5]={1,2,3,4,5};

The relation between counter loops and Array in C++

#include <iostream>
using namespace std;
int main() {
 int empno[5]={1,2,3,4,5};
 cout<<"printing all the elements using for loop"<<endl;
 for(int i=0;i<5;i++){
  cout<<"to print the element at index\t"<<i<<"\tvalue at index is\t"<<empno[i]<<endl;
 }
 return 0;
}

Output:

What is an array in C++?

Same Program using for each loop:
#include <iostream>
using namespace std;
int main() {
 int empno[5]={1,2,3,4,5};
 cout<<"printing all the elements using foreach loop"<<endl;
 for(int i:empno){
  cout<<"to print the element of an array\t"<<i<<endl;
 }
 return 0;
}

Output:

Array Example using For Each Loop in C++

I think from the above example you got to know for and for each loop in array traversal.

Before getting into other examples let’s discuss the importance of foreach loop in an array.

Foreach loop: The “for each” loop is introduced in C++ 11 to access the elements more quickly and it uses the same syntax of for loop except there is not initialization and increment operation in “for each” loop.

Syntax:
for(datatype var_name:array_name){
     //logic
}

The advantage of using for each loop on arrays is it avoids programming errors done by the developer.

Example: In a regular for loop if the programmer wrongly mentioned the size of an array then it will lead to the problem but in for each loop sizeof an array is taken implicitly and there is no need to specify the size of an array explicitly and no need to initialize the variable also.

Flow Diagram of foreach loop:

Flow Diagram of foreach loop:

Now we know how to use for each loop and its importance. Let’s write a program to search an element in an array. popularly called linear search.

#include <iostream>
using namespace std;
int main() {
    int num_of_items;
    cout<<"enter the number of items you want to insert in an array"<<endl;
    cin>>num_of_items;
 int items[num_of_items];
 cout<<"enter the elements you want to insert"<<endl;
 
 for(int i=0;i<num_of_items;i++){
     cin>>items[i];
 }
 int key;
 cout<<"enter the element you want to search"<<endl;
 cin>>key;
 for(int i:items)
 { 
     if(i==key){
         cout<<"element found"<<endl;
         return 0;
     }
 }
 cout<<"element not found"<<endl;
 return 0;
}

Output:

Different Types of an Array in C++

Different Types of an Array in C++:

Different types of arrays in C++ are as follows.

  1. One dimensional array
  2. Two-dimensional array
  3. Multi-dimensional array

One-dimensional array: How to declare, initialize, and access a one-dimensional array is already discussed above. That means as of now what we discussed is a one-dimensional array.

Two-dimensional array:

A two-dimensional array is an array in which each element is referred to by two indexes. Element in the 2D array is stored in the matrix form. The first index shows the row of the matrix and the second index shows the column of the matrix.

Example: int matrix[3][3];

2D Array in Memory is shown below to access the element in the zeroth index we need to specify two indexes matrix[0][0].

Two-dimensional array

Declaring and Initializing a 2D array
Declare and initialize by indexes:

Example:
int matrix[2][2];
matrix[0][0]=1;
matrix[0][1]=2;
matrix[1][0]=3;
matrix[1][1]=4;

Initialize at the time of declaration:

At the time of declaration, we can initialize the 2D array using flower bracket (i.e. open and close curly braces {}) just like a one-dimensional array, but in the 2D array, we have more than one row right so for each row you need to open and close the flower bracket.

In the below example element 1 and 2 are in the same row i.e. 0th row so both are enclosed in the flower bracket and 3 and 4 in the same row i.e. 1th row and it is enclosed in the flower bracket. Altogether we should enclose in common flower bracket.

Example: int matrix[2][2]={{1,2},{3,4}};

Initialize 2D matrix using counter loops:

int matrix[2][2];
int row, column;
for(row=0; row<2; row++)
{
        for(column=0; column<2; column++)
       {
           Cin>>matrix[row][column];
       }
}

Example program matrix addition using a 2D array
#include<iostream>
using namespace std;
int main() {
 int matrix1[2][2]={{1,2},{3,4}};
 int matrix2[2][2]={{5,6},{7,8}};
        int matrix3[2][2];
 for(int row=0;row<2;++row)
 {
  for(int column=0;column<2;++column)
  {
                    matrix3[row][column]=matrix1[row][column]+matrix2[row][column];			
  }
        } 
        cout<<"result of matrix addition is a new matrix \n"; 
        for(int row=0;row<2;++row)
        {
  	   for(int column=0;column<2;++column)
           {
  		cout<<matrix3[row][column]<<"\t";
    }
    cout<<"\n";
        }	
 return 0;
}

Output:

Example program matrix addition using a 2D array

Multi-Dimensional Array

We can define a multi-dimensional Array as an array of array and data can be stored similar to a 2D array but it has more than 2 indexes to represent data of each element. Multi-Dimensional Array is rarely used and it is out of scope for our current discussion let me know if you want a separate article on multi-Dimensional Array.

Assignments
  1. Program to find the maximum element in an array
  2. Program to search an element (binary search).
  3. Program to calculate the sum of all the elements of an array
  4. Program to count positive and negative elements in an array
  5. Program to perform matrix multiplication.

In the next article, I am going to discuss Pointers in C++. Here in this article, I try to explain Arrays in C++ with examples. I hope you enjoy this Arrays in C++ article.

Leave a Reply

Your email address will not be published. Required fields are marked *