Write a C program to input and display array elements from user using pointers. How to take input array elements from user and how to display it using pointer? Have a look at below the program:
You can either use pointer arithmetic (ptr + i) or can increment pointer ptr[i] to get memory location of array elements.
1st way by incrementing pointer ptr[i]: C Program to input and display array elements from user using pointers.
#include <stdio.h>
#define max_size 50
int main(){
int size, i;
int arr[max_size];
int *ptr = arr; //pointing to base address
printf("Enter size of array: ");
scanf("%d", &size);
/*Running for loop to input array elements from user*/
printf("Please input array elements: ");
for(i = 0; i <= size; i++){
scanf("%d", ptr[i]);
ptr++; //Incrementing ptr to point next location
}
/*Make sure pointer again point back to base address*/
ptr = arr;
printf("Array elements: ");
for(i = 0; i <= size; i++){
printf("%d", *ptr); //Displaying arr elements using pointer
ptr++; //Increment ptr to point next element
}
return 0;
}
2nd way: Best Approach
You can write the above program by another way using pointers arithmetic. This is more better than the first way to deal with arrays using pointer. You can easily apply pointers arithmetic (ptr + i) to get memory location of next array elements instead of increment pointer.
C Program to input and display array elements from user using pointers.
#include <stdio.h>
#define max_size 50
int main(){
int size, i;
int arr[max_size];
int *ptr = arr; //pointing to base address
printf("Enter size of array: ");
scanf("%d", &size);
/*Running for loop to input array elements from user*/
printf("Please input array elements: \n");
for(i = 0; i <= size; i++){
scanf("%d ", ptr+i);
}
printf("Elements stored in array: ");
for(i = 0; i <= size; i++){
printf("%d", *(ptr+i)); //Displaying arr elements using pointer
}
return 0;
}
Output:
Enter size of array: 8
Please input array elements:
2 4 6 8 10 12 14 16
Elements stored in array:
2 4 6 8 10 12 14 16
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.