0% found this document useful (0 votes)
2K views

C Program To Swap Two Arrays Using Pointers

This C program defines a function to swap two integer arrays of size n using pointers. It takes in two integer pointers and the size n as arguments. The function iterates through both arrays, swapping each element using a temporary integer variable. In main, it allocates memory for two integer arrays, gets input from the user to populate the arrays, calls the swap function, and prints out the swapped arrays.

Uploaded by

Aree Kabeto
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

C Program To Swap Two Arrays Using Pointers

This C program defines a function to swap two integer arrays of size n using pointers. It takes in two integer pointers and the size n as arguments. The function iterates through both arrays, swapping each element using a temporary integer variable. In main, it allocates memory for two integer arrays, gets input from the user to populate the arrays, calls the swap function, and prints out the swapped arrays.

Uploaded by

Aree Kabeto
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

C program to swap two arrays using pointers

#include <stdio.h>
#include <stdlib.h>
/* swaps two arrays using pointers */
void swapTwoArrays(int *arr1, int *arr2, int n) {
int i, temp;
for (i = 0; i < n; i++) {
temp = *(arr1 + i);
*(arr1 + i) = *(arr2 + i);
*(arr2 + i) = temp;
}
return;
}
int main() {
int *arr1, *arr2, i, j, n;
/* get the order of the arrays from the user */
printf("Enter the order of the arrays:");
scanf("%d", &n);

/* dynamically allocate memory to store elements */


arr1 = (int *) malloc(sizeof(int) * n);
arr2 = (int *) malloc(sizeof(int) * n);
/* input elements for first array */
printf("Enter data for first array:\n");
for (i = 0; i < n; i++) {
printf("Array1[%d] : ", i);
scanf("%d", (arr1 + i));
}
/* input elements for second array */
printf("Enter data for second array:\n");
for (i = 0; i < n; i++) {
printf("Array2[%d] :", i);
scanf("%d", arr2 + i);
}
/* swap the elements in the given arrays */
swapTwoArrays(arr1, arr2, n);

/* print the elements in the first array */


printf("Elements in first array:\n");
for (i = 0; i < n; i++) {
printf("%d ", *(arr1 + i));
}
printf("\n");

/* print the elements in the second array */


printf("Elements in second array:\n");
for (i = 0; i < n; i++) {
printf("%d ", *(arr2 + i));
}
printf("\n");
return 0;
}

You might also like