This blog is under construction

Tuesday, 23 July 2013

C program to reverse an array

Write a C program to reverse an array.


  #include <stdio.h>
  #define MAXLIMIT 256

  int main() {
        int i, j, n, temp, array[MAXLIMIT];

        /* get the number of elements in i/p array */
        printf("Number of elements in the array:");
        scanf("%d", &n);

        /* boundary check - to avoid stack overrun */
        if (n > MAXLIMIT || n < 0) {
                printf("Boundary Exceeded!!\n");
                return 0;
        }

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

        j = n - 1;
        i = 0;

        /* reversing the array */
        while (i < j) {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
                i = i + 1;
                j = j - 1;
        }

        /* printing the contents of the reversed array */
        printf("Contents of the i/p array after reversing:\n{");
        for (i = 0; i < n; i++) {
                printf("%d, ", array[i]);
        }
        printf("\b\b}\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Number of elements in the array:5
  Enter your array elements:
  Array[0]: 10
  Array[1]: 20
  Array[2]: 30
  Array[3]: 40
  Array[4]: 50

  Contents of the i/p array after reversing:
  {50, 40, 30, 20, 10} 


No comments:

Post a Comment