C++ Array

Here you will learn about array, it’s declaration, initialization in C++ programming.

In C++ programming, it was hard to handle numerous data of same type.

For example: you have to store information of 50 students, e.g: their monthly fee amount. So to solve this problem in C++ you can create an integer type array of 50 elements.

Array is a collection of data that could handle the same type of data efficiently.

For example:

Int income[50];

After it’s declaration the size & type of array couldn’t change.

Declaration of C++ Array

Datatype arrayname[arraysize]

Char grade[5];

Here we declare an array, named as grade, of character type. Which could store 5 char type values.

Initialization of C++ Array

It is possible to initialization an array during declaration.

For example:

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

Or

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

Array with index;

Jack[0]=1

Jack[1]=2

Jack[2]=3

Jack[3]=4

Jack[4]=5

How to access the elements of C++ array?

By using indexes you can access elements in C++ array.

As you had declare grade[5], so the first element is stored in grade[0], second is stored in grade[1] & so on…

  • Array’s 1st index is zero not 1.
  • Suppose the starting address of an array grade[0] is 5025, the address of grade[1] will be 5026, address of grade[2] will be 5027 & so on. Increment of 1 is because the size of char is 1 byte.
  • If the size of C++ array is n, to access the last element ,(n-1) index is used.

 

How to display and insert element of an Array?

Example: C++ Array

learn c++ array

  • Here for storing any element in specific array;

          Arr[3]=8;

  • Taking element from user;

         Cin>>arr[i];

  • For printing an array;

         Cout<<arr[i];

  • Taking 4th element from user;

         Cin>>arr[3];

  • For printing 3rd element of an array;

         Cout<<arr[2];

  • Printing last element of an array;

         Cout<<arr[n-1];

Here n is the size of an array.

Example: C++ Array

array learn c++

If you are trying to access element outside it’s bound then compiler may not show any error but you may have unexpected output.