This is a C Program to accept an array & swap elements using pointers.
The program will implement an array and will swap the elements of the array. Swapping is done using pointers.
1. Declare an array and define all its elements.
2. Create a function with two parameters i.e. two pointer variables.
3. Inside this function, first create a temporary variable. Then this temporary variable is assigned the value at first pointer.
4. Now, value at first pointer changes to the value at second pointer.
5. And value at second pointer changes to the value of temporary variable.
6. This way swapping is done and in main() function, we need to pass two pointer variables pointing the element which we need to swap.
Here is source code of the C program to accept an array & swap elements using pointers. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
* C program to accept an array of 10 elements and swap 3rd element
* with 4th element using pointers and display the results.
void swap34(float *ptr1, float *ptr2);
int i, n;
printf("How many Elements...\n");
printf("Enter Elements one by one\n");
for (i = 0; i < n; i++)
scanf("%f", x + i);
/* Function call:Interchanging 3rd element by 4th */
swap34(x + 2, x + 3);
for (i = 0; i < n; i++)
printf("X[%d] = %f\n", i, x[i]);
/* Function to swap the 3rd element with the 4th element in the array */
void swap34(float *ptr1, float *ptr2 )
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
1. Declare an array and define all the elements according to its size taken from users.
2. Now create a function passing two pointer variables of float type as parameters to this function.
3. Inside a function a variable temp is declared of float type, which will store the value pointed by first pointer variable.
4. Now value pointer by first pointer variable is changed to the value pointed by second pointer variable, and value pointer by second variable is change to the value of temp variable.
5. Exit the function.
6. In the main() method, call this function with pointers pointing to those two element which you want to swap.
How many Elements... 4 Enter Elements one by one 23 67 45 15 Resultant Array... X = 23.000000 X = 67.000000 X = 15.000000 X = 45.000000
Sanfoundry Global Education & Learning Series – 1000 C Programs.