Here in this program, an array of five elements is declared and the elements of that array are accessed using a pointer.
In C++, an array is a variable that can store multiple values of the same type. the size and type of arrays cannot be changed after their declaration.
dataType arrayName[arraySize];
each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices.
array[index]
In C++, pointers are variables that store the memory addresses of other variables.
int *pointVar;
. Not only can a pointer store the address of a single variable, but it can also store the address of cells of an array.
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
.
Initialize the value of I to 0. Check for the condition i<5 and increment the value of I by 1 on each iteration.
Get the data into each ith position.
Access the elements on the array a[5] by using the pointer *(a + i)
for loop
can be used to access the entire elements from the beginning.
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