C program to input and print array elements using pointers
C program to input and print array elements using pointers. Learn step-by-step how to utilize pointers to enhance memory management and optimize array manipulation.
Pointers are handy when working with arrays as they allow efficient traversal and manipulation of array elements. In this article, we'll explore how to write a C program to input and print array elements using pointers.
Write a C Program to Input and Print Array Elements Using Pointers
Now, let's proceed to write a C program that prompts the user to input array elements and then prints them using pointers.
#include <stdio.h>
int main() {
int n, i, arr[100];
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
// Input array elements using pointers
for (i = 0; i < n; i++) {
scanf("%d", &(*(arr + i))); // Equivalent to &arr[i]
}
printf("Array elements are:\n");
// Print array elements using pointers
for (i = 0; i < n; i++) {
printf("%d ", *(arr + i)); // Equivalent to arr[i]
}
return 0;
}
We can also declare array as pointer, in that case we can avoid passing specific size to declared array.
#include <stdio.h>
int main() {
int n, i, *arr;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
// Input array elements using pointers
for (i = 0; i < n; i++) {
scanf("%d", &(*(arr + i))); // Equivalent to &arr[i]
}
printf("Array elements are:\n");
// Print array elements using pointers
for (i = 0; i < n; i++) {
printf("%d ", *(arr + i)); // Equivalent to arr[i]
}
return 0;
}
Output -
Enter the number of elements: 5
Enter 5 elements:
5
4
3
2
1
Array elements are:
5 4 3 2 1
Explanation:
- We begin by declaring variables
n
andi
to store the number of elements and iterate over the array, respectively. - The user is prompted to enter the number of elements in the array.
- We declare an array
arr
of sizen
. - Using a loop, we prompt the user to input
n
array elements. Here, we use pointers to access the memory locations of array elements. - Similarly, we use pointers to traverse the array and print its elements.
Key Concepts Illustrated:
- Pointer Arithmetic: In C, we can use pointer arithmetic to navigate through array elements efficiently. In the program,
(arr + i)
is equivalent toarr[i]
, and both expressions access thei
th element of the array. - Dynamic Memory Allocation: The program demonstrates dynamic memory allocation by allowing the user to specify the size of the array at runtime using the variable
n
.