In this C++ program, an array of five elements is declared and are accessed using a pointer.
An array is a datatype that can able to store some elements of the same datatype in continuous memory locations. The array will be declared as
dataType arrayName[arraySize];.
An array has elements that can be accessed by using a variable which is called as an Index variable.
array[index]
In C++, pointers are variables that can able to store the address of another variable. A pointer will be declared using the asterisk (*) sign, int *pointVar.
int *ptr;
int arr[5];
// store the address of the first
// element of arr in ptr
ptr = arr
Declare an integer-type array of size 5 and ask the user to enter the elements. Read the elements into the array a[5] by using a for loop
. Use another for loop to access the elements on the array by using the pointer, and display the elements.
Step 1: Call the header file iostream.
Step 2: Use the namespace std.
Step 3: Open the integer type main function; int main().
Step 4: Declare integer type array a[5]
Step 5: Ask the user to enter the elements.
Step 6: Read the elements into the array
Step 7:Access the elements using the pointer and display them on the screen.
Step 8: Exit
#include <iostream>
using namespace std;
int main()
{
int a[5];
cout << "Enter elements: ";
for(int i = 0; i < 5; ++i)
cin >> a[i];
cout << "You entered: ";
for(int i = 0; i < 5; ++i)
cout << endl << *(a + i);
return 0;
}
Enter elements: 6 3 5 6 4 You entered: 6 3 5 6 4