This C program demonstrates how to accept an array of elements and swap the elements at desired positions using pointer. Before going into the program, we need to know more about pointers in C, and how this swapping of elements in an array can be executed using pointers.
A pointer is a variable that can able to store the address of another variable. Below are the steps to use a pointer in a program
As a result, we get the array elements swapped at the desired position.
STEP 1: Include the header files to use the built-in functions in the C program.
STEP 2: Declare the Array x[20] as float and variables i, n, p1,p2 as integers.
STEP 3: Declare the function swap(float *ptr1, float *ptr2).
STEP 4: Read the number of elements into the variable n.
STEP 5: Read the elements of the Array into the array x+i using for loop
.
STEP 6: Now call the Function swap(x+p1,x+p2) to interchange the p1 element by p2th.
STEP 7: Display the resultant Array as x[i] using for loop
.
Function void swap(float *ptr1,float *ptr2)
STEP 1: Declare the variable temp as the float.
STEP 2: Assign temp=*ptr1.
STEP 3: *ptr1=*ptr2.
STEP 4: *ptr2=temp
To swap elements of an array using pointers in C programming, we have to learn the below concepts. We recommend you to learn those for better understanding
#include <stdio.h>
void main() {
float x[20];
int i, n,p1,p2;
void swap(float * ptr1, float * ptr2); /* Function Declaration */
printf("How many Elements...\n");
scanf("%d", & n);
printf("Enter Elements one by one\n");
for (i = 0; i < n; i++) {
scanf("%f", x + i);
}
printf("Enter 2 Positions for swapping\n");
scanf("%d %d", &p1;,&p2;);
swap(x + p1, x + p2); /* Function call:Interchanging p1th element by p2th */
printf("\nResultant Array...\n");
for (i = 0; i < n; i++) {
printf("X[%d] = %f\n", i, x[i]);
}
} /* End of main() */
/* Function to swap any 2 elements in the array */
void swap(float * ptr1, float * ptr2) /* Function Definition */ {
float temp;
temp = * ptr1;
* ptr1 = * ptr2;
* ptr2 = temp;
}
How many Elements... 10 Enter Elements one by one 10 20 30 40 50 60 70 80 90 100 Enter 2 Positions for swapping 3 7 Resultant Array... X[0] = 10.000000 X[1] = 20.000000 X[2] = 30.000000 X[3] = 80.000000 X[4] = 50.000000 X[5] = 60.000000 X[6] = 70.000000 X[7] = 40.000000 X[8] = 90.000000 X[9] = 100.000000