In this tutorial, we shall go through some of the most used Array Operations like initializing an array, finding array length, traversing the array using a loop statement, printing the array, etc.

C++ Array Operations

1. Initialize Array

To initialize a C++ Array, use square brackets after variable name to denote that it is an array, and assign the variable with list of elements.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int arr1[] = {7, 3, 8, 7, 2};

   //print arrays
   for (int i=0; i < sizeof(arr1)/sizeof(*arr1); i++) {
      cout << arr1[i] << "  ";
   }
}

Output

7  3  8  7  2

Complete Tutorial – C++ Initialize Array

2. Array Length

To get length of C++ Array, you may use any looping statement, iterate over each of the element and increment the counter for length during each iteration.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int arr[] = {3, 5, 8, 13, 21, 34};
   int len = 0;

   for (int n: arr)
      len++;

   cout << len;
}

Output

6

Complete Tutorial – C++ Array Length

3. Print Array

To print all Array Elements, you can use any of the C++ loop statements.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int arr[7] = {25, 63, 74, 69, 81, 65, 68};
   
   for (int element: arr) {
      cout << element << "  ";
   }
}

Output

25  63  74  69  81  65  68

Complete Tutorial – C++ Print Array

4. Loop through Array Elements

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int arr[7] = {25, 63, 74, 69, 81, 65, 68};
   
   int i=0;
   while (i < 7) {
      cout << arr[i] << "  ";
       i++;
   }
}

Output

25  63  74  69  81  65  68

Complete Tutorial – C++ Loop through Array Elements

Conclusion

In this C++ Tutorial, we have learned some of the Array Operations, with examples and detailed tutorials.