This blog is under construction

Wednesday, 24 July 2013

C program to swap two arrays

Write a C program to swap two arrays.


  #include <stdio.h>
  #define MAXLIMIT 256

  int main() {
        int arr1[MAXLIMIT], arr2[MAXLIMIT];
        int i, n, temp;

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

        /* get the entries for first array */
        printf("Enter your first array entries:\n");
        for (i = 0; i < n; i++) {
                printf("Array1[%d]: ", i);
                scanf("%d", &arr1[i]);
        }

        /* get the entries for second array */
        printf("Enter your second array entries:\n");
        for (i = 0; i < n; i++) {
                printf("Array2[%d]: ", i);
                scanf("%d", &arr2[i]);
        }

        /* swap the contents of first and second arrays */
        for (i = 0; i < n; i++) {
                temp = arr1[i];
                arr1[i] = arr2[i];
                arr2[i] = temp;
        }

        /* print the contents in first array */
        printf("\nContents in first array:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", arr1[i]);
        }

        /* print the contents in second array */
        printf("\n\nContents in second array:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", arr2[i]);
        }
        printf("\n");

        return 0;
  }



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

  Enter your second array entries:
  Array2[0]: 100
  Array2[1]: 200
  Array2[2]: 300
  Array2[3]: 400
  Array2[4]: 500

  Contents in first array:
  100  200  300  400  500 

  Contents in second array:
  10  20  30  40  50 


No comments:

Post a Comment