Write a C program to read and print array elements using a pointer. In this c example, we will print array elements using a pointer and for loop.
- arr[0] is equivalent to *arr
- Insert Element at arr[1] = arr + 1 and Printing arr[1] = *(arr + 1)
- Insert Element at arr[2] = arr + 2 and Printing arr[2] = *(arr + 2)
#include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; int *parr = arr; for (int i = 0; i < 5; i++) { printf("%d ", *(parr + i)); } printf("\n"); }
10 20 30 40 50
This c example allows the user to enter the size and array elements. Next, this c program reads and prints the array elements using a pointer.
#include <stdio.h> int main() { int Size, i; printf("Please Enter the Array size = "); scanf("%d", &Size); int arr[Size]; int *parr = arr; printf("Enter the Array Elements = "); for (i = 0; i < Size; i++) { scanf("%d", parr + i); } printf("Printing Array Elements using Pointer\n"); for (i = 0; i < Size; i++) { printf("%d ", *(parr + i)); } printf("\n"); }
In this c example, the insertArrayItem accepts the pointer array and stores or reads the user input array elements. Next, the printArrayItem prints the array items using a pointer.
#include <stdio.h> void insertArrayItem(int *parr, int Size) { for (int i = 0; i < Size; i++) { scanf("%d", parr + i); } } void printArrayItem(int *parr, int Size) { for (int i = 0; i < Size; i++) { printf("%d ", *(parr + i)); } } int main() { int Size, i; printf("Please Enter the size = "); scanf("%d", &Size); int arr[Size]; printf("Enter the Elements = "); insertArrayItem(arr, Size); printArrayItem(arr, Size); printf("\n"); }
Please Enter the size = 7
Enter the Elements = 22 98 44 276 86 -14 11
22 98 44 276 86 -14 11