Google News
logo
C++ Program to Access Elements of an Array Using Pointer
In the following example of C++ program that demonstrates how to access elements of an array using pointers :
Program :
#include <iostream>
using namespace std;

int main() {
   int arr[5] = {10, 20, 30, 40, 50};
   int *ptr;

   ptr = arr;

   cout << "Elements of the array are: ";
   for(int i=0; i<5; i++) {
      cout << *ptr << " ";
      ptr++;
   }

   return 0;
}


In this program, we have an integer array arr with five elements. We declare a pointer variable ptr of integer type, which points to the first element of the array.

We then use a for loop to iterate over the array elements. Inside the loop, we print the value pointed to by the ptr using the * operator, and then increment the pointer to point to the next element of the array.

Output :
Elements of the array are: 10 20 30 40 50