Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to Access Array Elements Using Pointer

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to Access Array Elements Using Pointer

Objective

Write a C++ program to access array elements using Pointers.

Algorithm / Approach

  1. Declare an array and read 5 elements into it.
  2. Run a for loop from 0 to 4.
  3. Access and print the elements using pointer arithmetic: *(arr + i).
main.cpp
#include<iostream>
using namespace std;
int main( ) {
 int arr[5], i;
 cout<<"Enter Elements of Array:";
 for(i=0;i<5;i++){
  cin>>arr[i];
 }
  cout<<"You have entered : ";
 for(i=0;i<5;i++){
   cout<< *(arr+i)<<"  ";
 }
 return 0;
}

Expected Output

Enter Elements of Array : 1 4 6 7 8
You have entered : 1 4 6 7 8

Explanation of the Program

  • Because arrays are just contiguous blocks of memory, arr[i] is literally just syntactic sugar for *(arr + i).
  • arr points to the base memory address. + i shifts the address forward by i slots. The * dereferences that calculated memory address to get the data inside.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT