C++

C++ Arrays – Detailed Instructions From [A-Z]

A group of related objects kept in close proximity to one another in memory is called an array. Sometimes in programming, a straightforward variable is insufficient to hold all the data. As an illustration, suppose we need to store the grades of 500 students. Since it is impractical to use 500 individual variables for this task, we can build an array with a size of 500 that can accommodate all of the students’ grades.

Making a C++ array declaration

Declaring an array can be done in a few different ways.

Method 1:

int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

Method 2:

int arr[] = {10, 20, 30, 40, 50};

Method 3:

int arr[5] = {10, 20, 30, 40, 50};

Making Use of Array Elements

The first array element is at index 0, the second at index 1, and so forth because the array index starts at 0. This data can be used to show the array elements. View the code here:

#include <iostream>
using namespace std;

int main(){
   int arr[] = {11, 22, 33, 44, 55};
   cout<<arr[0]<<endl;
   cout<<arr[1]<<endl;
   cout<<arr[2]<<endl;
   cout<<arr[3]<<endl;
   cout<<arr[4]<<endl;
   return 0;
}

Output:

11
22
33
44
55

Although this code executed without a hitch, it is not advised to display an array’s elements all at once. This is acceptable when you need to access a specific array element, but if you want to see all the elements, you should use a loop like this:

#include <iostream>
using namespace std;

int main(){
   int arr[] = {11, 22, 33, 44, 55};
   int n=0;
  
   while(n<=4){
      cout<<arr[n]<<endl;
      n++;
   }
   return 0;
}

Related Articles

Leave a Reply

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

Back to top button