Coders Packet

C++ Arrays with Example

By Kinjal Pagar

An array is used to store similar type of data. In this tutorial, we are going to discuss Array in C++. Declaration of Array, Accessing elements from an array, etc.

The array is the collection of similar data types of elements and elements can be randomly accessed using indices of an array. Arrays can be used to store different data types including Int, Float, Double, Char, etc.

To declare an array in C++ first we need to define the data type of Array Variable. It can be Int, Float, String, Double, etc. Secondly, assign the name of the Array  followed by the square brackets [] and specify the size of the array into the square brackets : 

Syntax :

Data_Type  Array_Name[Array_Size];

Whereas the Array_Size must be an Integer variable.

Example :

Int My_Array[5];

 

We have 5 elements of type Integer array My_array.

Array structure of 5 elements :

 

Index [0]

Index[1]

Index[2]

Index[3]

Index[4]

 

Index 0 is the first while Index[4] is the last for Array size 5. We can store the integer values in our My_Array as its type is Integer. We can not add new elements in the array or cannot increase Array size at runtime. For these, we need to use Vector in C++.

 

Let’s assign data to the Array Variable:

Syntax:

              Data_Type Array_Name [N] = {Value1, Value2, Value3,….,ValueN}

 

Example :

              Int Integer_Array[3] = {100, 200, 300};

              String String_Array[3] = {“First”, “Second”, “Third”};

 

In this way, we can assign the data to the array variable. To access this data we need to refer index number. This statement access the value of the first element in fruits :

 

String Fruits[5] = {“Apple”, “Banana”, “Cherries”, “Grapes”, “Mango”};

Cout<<Fruits[0];

 

Whereas,

Fruits[0] = Apple

Fruits[1] = Banana

Fruits[2] = Cherries

Fruits[3] = Grapes

Fruits[4] = Mango

 

But here we are accessing fruits by printing each index individually. To reduce the code of length we can use Loop to access the elements from an array. Here is one example with source code :

 

#include 
#include 

using namespace std;

int main()
{
    string Fruits[5] = {"Apple", "Banana", "Cherries", "Grapes", "Mango"};
    for(int i = 0; i < 5; i++) 
    {
        cout << Fruits[i] << "\n";
    }
    return 0;
}

In this way we have learned About Array, Array Declaration, Accessing elements from Array.

Thank You.

 

Download Complete Code

Comments

No comments yet