This blog is under construction

Monday, 22 July 2013

C program to reverse an array using pointers

Write a C program to reverse an array using pointers.


  #include <stdio.h>
  #include <stdlib.h>

  int main() {
        int i, j, n, *num, temp;

        /* get the number of elements from the user */
        printf("Enter the number of elements:");
        scanf("%d", &n);

        num = (int *)malloc(sizeof(int) * n);

        /* input array elements from the user */
        printf("Enter your inputs:\n");
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", (num + i));
        }

        i = 0, j = n - 1;

        /* reverse the given array */
        while (i < j) {
                temp = *(num + i);
                *(num + i) = *(num + j);
                *(num + j) = temp;
                j--, i++;
        }

        /* print the results */
        printf("\nReversed the given array:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", *(num + i));
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements:4
  Enter your inputs:
  Data[0]: 10
  Data[1]: 20
  Data[2]: 30
  Data[3]: 40

  Reversed the given array:
  40 30 20 10 


No comments:

Post a Comment