Swapping refers to the interchange of the values of two. In this C program, we will use the following features –
- Functions
- Float
- Pointers
We will take two floating variables from the user and pass them to a function swap() as a reference. We will use a temp variable inside the function and then swap the value.
Here is the example of C program –
- m = 5, n = 10
- Passing to swap function as reference – &m , &n.
- Inside the function, temp = *ptr1 // which is 5
- *ptr1 = *ptr2 // here we are giving *ptr2 value into *ptr1, so now its 10
- *ptr2 = temp //here *ptr2 = 5
- so the returned value is m = 10 and n = 5.
#include <stdio.h>
void swap(float *ptr1, float *ptr2);
void main()
{
float m, n;
printf("Enter the values of M and N \n");
scanf("%f %f", &m, &n);
printf("Before Swapping:M = %5.2ftN = %5.2f\n", m, n);
swap(&m, &n);
printf("After Swapping:M = %5.2ftN = %5.2f\n", m, n);
}
/* Function swap - to interchanges the contents of two items */
void swap(float *ptr1, float *ptr2)
{
float temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}