Home >>Cpp Programs >CPP Program for different ways to print array elements
In this example, we will see a C++ program through which we can print array elements in different ways.
We can print the elements of an array in many ways like Subscription notation, offset notation with array name, pointer subscription notation, and offset notation with pointer name.
Program:
// Different ways of accessing array elements in C++
#include <iostream.h>
using namespace std;
int main(void)
{
const int len = 5;
int intArray[len] = { 1, 2, 3, 4, 5 };
int* ptr;
cout << "Array elements (Subscript Notation) : " << endl;
for (int i = 0; i < len; i++)
cout << "intArray[" << i << "] = " << intArray[i] << endl;
cout << "\nArray elements (Pointer/Offset Notation): \n";
for (int index = 0; index < len; index++)
cout << "*(intArray + " << index << ") = " << *(intArray + index) << endl;
ptr = intArray;
cout << "\nArray elements (Pointer Subscript Notation): \n";
for (int i = 0; i < len; i++)
cout << "ptr[" << i << "] = " << ptr[i] << endl;
cout << "\nArray elements (Pointer/Offset Notation): \n";
for (int index = 0; index < len; index++)
cout << "*(ptr + " << index << ") = " << *(ptr + index) << endl;
cout << endl;
return 0;
}