- 2072 Kartik · 6 marks
Reverse array and display via pointer
Short answer
Function reverseArray uses two pointers (start and end). While i < j, swap *i and *j, then move pointers inward. It returns the array pointer. Main calls it, then prints reversed elements using *(p+i). Example output: 5 4 3 2 1.
Write a C program that calls reverse array () to reverse the array and return the array and display the element of reversed array using pointer.
Logic. reverseArray(int *a, int n) uses two pointers: i at the first element and j at the last (a + n - 1). While i < j the values *i and *j are swapped, then i moves forward and j backward. The function returns the pointer to the array, and main() displays the reversed elements with *(p + i).
#include <stdio.h>
/* reverses the array in place and returns its address */
int *reverseArray(int *a, int n)
{
int *i = a, *j = a + n - 1, t;
while (i < j) {
t = *i; *i = *j; *j = t;
i++; j--;
}
return a;
}
int main(void)
{
int a[50], n, *p;
printf("Enter N: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
p = reverseArray(a, n);
printf("Reversed array: ");
for (int i = 0; i < n; i++)
printf("%d ", *(p + i));
printf("\n");
return 0;
}
Sample run
Input: 5 1 2 3 4 5
Enter N: Enter 5 elements: Reversed array: 5 4 3 2 1
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Second largest element using pointer · Computer Programming, chapter 9
- Pass student array; display passed students · Computer Programming, chapter 7
- Relation between array and pointer · Computer Programming, chapter 9 · asked 5×
- Accessing array elements using pointer · Computer Programming, chapter 9
- Can a function return an array · Computer Programming, chapter 7
- Correct program: case array and average · Computer Programming, chapter 3
- Two-element array and end fire pattern · Propagation and Antenna, chapter 2
- Two-element array: broadside and end fire · Propagation and Antenna, chapter 2
- PC-to-phone calls via internet and PSTN · Telecommunications, chapter 8
- 8086 ALP: largest and smallest, display · Microprocessor, chapter 3