WAP to Access Array Elements Using Pointer
Objective
Write a C++ program to access array elements using Pointers.
Algorithm / Approach
- Declare an array and read 5 elements into it.
- Run a
forloop from 0 to 4. - 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). arrpoints to the base memory address.+ ishifts the address forward byislots. The*dereferences that calculated memory address to get the data inside.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)