For a better understanding, we always recommend you to learn the basic topics of C programming listed below:
In this c program, we have to accept an array of elements and swap the elements at the third position with the element of the fourth position using a pointer. Before going into the program, we have to know more about pointers and how this swapping of elements in an array can be executed using pointers.
A pointer is simply a variable whose value is the address of another variable. Also, we have to know how we use a Pointer in a program. The steps are.
Given below steps are used in the program to perform Swapping of elements
In this way, we perform swapping in this C program.
STEP 1: Include the header files to use the built-in functions in the C program.
STEP 2: Declare the Array x[10] as float and i, n as an integer.
STEP 3: Define the function swap34(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: Call the Function swap34(x+2,x+3) to interchange the 3rd element by 4th.
STEP 7: Display the resultant Array as x[i] using for loop
.
Function void swap34(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
#include <stdio.h>
void main() {
float x[10];
int i, n;
void swap34(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);
}
swap34(x + 2, x + 3); /* Function call:Interchanging 3rd element by 4th */
printf("\nResultant Array...\n");
for (i = 0; i < n; i++) {
printf("X[%d] = %f\n", i, x[i]);
}
} /* End of main() */
/* Function to swap the 3rd element with the 4th element in the array */
void swap34(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 Resultant Array... X[0] = 10.000000 X[1] = 20.000000 X[2] = 40.000000 X[3] = 30.000000 X[4] = 50.000000 X[5] = 60.000000 X[6] = 70.000000 X[7] = 80.000000 X[8] = 90.000000 X[9] = 100.000000