Arrays in c++

Arrays in c++

We have studied storing data in variables so far. Every variable has a unique identifier and stores one single data value which can be overwritten. Therefore, if we want to store a large collection of data of the same type, we need a large number of variables. It is a very slow and steady approach to deal with such a scenario. So, c++ has a data structure called arrays which make it easy to do. Arrays in c++ are sequence or collection of contiguous memory locations used to store data of the same type with a single identifier. Arrays are also called the collection of variables of the same type with the same name(identifier). Arrays are transversed with an integer value called index. The main feature of the array is its contiguous/ continuous memory locations. it makes arrays easier to access. If we know the starting address then we can transverse the whole array.

Why we need Arrays?

Consider an example of storing marks of 100 students. We need 100 different variables to store this data. It's a very slow and time-consuming approach which is not recommended. Displaying this data stored in variables is also very time taking. Instead of 100 variables, we can declare an array of 100 elements in just one line. It's very easy to store and display data in an array with indexes.

How to declare and initialize an array?

When it comes to declaring and initializing an array,  there are multiple ways to do it depending on the circumstances you are dealing with. Let's start learning all the possible ways.

  1. If you want to simply declare an array and store the user's input values in it, you can simply write the data type, identifier, and the size of an array in square brackets. Then you can use for loop to take input of the user in the array.
  2. But If you want to declare an array and initialize hardcoded values, you can write empty square brackets and equals it to the values enclosed in curly braces. If you write 4 values inside curly braces, the compiler will create an array of size 4. It means that in this method, the array size is equal to the number of values enclosed in braces.
  3. Another way of declaring an array is to write the size of the array in square brackets and equals it to the values/data enclosed in curly braces. In this method, we cannot initialize values more than the array size.
  4. There is another possible way of declaring and initializing an array. The declaration is the same as in the first point by specifying the size in square brackets. After the declaration, elements of the array are initialized through the assignment operator. This method is not recommended but can be useful in some scenarios.
The below programs is written to explain all the above method of declaration and initialization.

    #include <iostream>
    using namespace std;
    int main()
    {
     //------------#1---------------
     int ArrofStdnt1[5];
     for (int i = 0; i < 5; i++)
     {
      cin>>ArrofStdnt1[i];
     }
     //------------#2----------------
     int ArrofStdnt3[] = { 3,5,7,9,8 };
     
    //------------#3---------------
     int ArrofStdnt2[5] = {3,5,7,9};
     // since the last element is not initialized so it is equaled to 0.
    
     
     //------------#4----------------
     int ArrofStdnt4[5];
     ArrofStdnt4[0] = 4;
     ArrofStdnt4[1] = 3;
     ArrofStdnt4[2] = 8;
     ArrofStdnt4[3] = 7;
     ArrofStdnt4[4] = 9;
     system("pause");
     return 0;
    }
    


    What is the Array index?

    The array index is an integer value that is used to access different elements of an array. It starts from zero to the size of the array. If you have an array of size 5 then indexes will be from 0 to 4.e.g.(0 to access the first element of the array and 4 to access the last one).

       How to access an element of an Array?

      In c++, we can access each of the elements of the array through its index. If we want to access the first element of the array"arr", we can write arr[0] to access it. We can access the fourth element like this arr[3]. We can perform different operations on the array element though this way. For example, we can reinput the value of this array element cin>>arr[0];. We can add, subtract, multiply, etc any number with the array element like arr[3]=arr[3] +5;. We can also print the data of the array element like cout<<arr[3];.To summarize, we can access elements of the array individually and perform different operations on it though its index.


      #include <iostream>
      using namespace std;
      int main()
      {
       //----array declaration and initialization------
       int ArrofStdnt[5] = {3,5,7,9};
       //----displaying last element of array----------
       cout << ArrofStdnt[4];
       //----reinput of 2nd element--------------------
       cin >> ArrofStdnt[1];
       //---------addition operation-------------------
       ArrofStdnt[3] += 5;
       system("pause");
       return 0;
      }
      

      How to access the whole array?

      In the above paragraph, we discussed how can we access individual elements of the array and perform different operations on it like displaying, etc. Now we will discuss how can we access the whole array data and perform different operations on it like displaying, sorting, searching, etc. We use for loop to start accessing data of the array from the first index 0 to the last index. The below code is a very good example of accessing the whole array and performing different operations on it.

      #include <iostream>
      using namespace std;
      int main()
      {
       //----Array declaration and initialization------
       int ArrofStdnt[5] = {3,5,7,9,4};
       //----Accessing the whole array through loop----
       for (int i = 0; i < 5; i++) {
       //----Performing different operation-----------
        ArrofStdnt[i] *= 3;
        cout << ArrofStdnt[i] << endl;
       }
       system("pause");
       return 0;
      }
      
      Here is the stepwise explanation of the above code.

      • First and foremost, we declared and initialized an array of integers called ArrofStdnt of size 5 with the third method of declaration and initialization as mentioned earlier in this article.
      • Then we run a for loop to access the whole array.
      • In the body of the loop, we perform two operations on the whole array, multiplying 3 with the whole array and displaying the whole array.
      • In the first iteration of the above code when the value of loop counter i is zero, the array element at index zero is multiplied with 3 and then printed with cout statement written in the next line. Then at the end of the first iteration, the loop counter value is incremented and is now 1. 
      • Now in the second iteration, the array element at index 2 is multiplied by 3 and then printed. Again the loop counter is incremented at the end of the second iteration.
      •  Third, fourth, and fifth iterations are executed in the same way as above two. 
      note that the number of iteration will always be equal to the array size. In the above example, the array size was five so we executed five iterations from index 0 to 4.

      How to store user input values in an array?

      To input values in the whole array, we use "cin" statements inside a loop body. The index is also written after the array identifier to store data at the specified location of the array. Let's see how we input data in an array with the below code example.

      #include <iostream>
      using namespace std;
      int main()
      {
       //----Array declaration-----------------
       int ArrofStdnt[5];
       //----initializing user input values----
       for (int i = 0; i < 5; i++) {
        cout << "enter marks of the student#" << i;
        cin >> ArrofStdnt[i];
       }
       system("pause");
       return 0;
      }
      

      How an array is stored in Memory?

      Let's say we want to create an array of integers to store marks of 5 students. We will need an array of size 5. It does not mean we reserved 5 bytes of memory. As we know the size of the integer is 4 bytes. So,  5 consecutive/continuous/contiguous blocks of size 4 bytes each are reserved in memory. It means that the total reserved space for this array in memory is 5*4=20 bytes. 

      This article was about the basic concepts of arrays. There are many complex concepts related to arrays like dynamic arrays, multidimensional-array, passing arrays to functions, etc. We will discuss all these topics in our upcoming articles.



      Post a Comment

      0 Comments