C Program to swap the values of two integers


February 9, 2023, Learn eTutorial
1114

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

How to swap the values of two integers in C

In this C program, we need to swap the values in two variables, which means if a has a value of 40 and b has 50 after swapping we need to have the value of a to be 50 and b to be 40. In this C program, we are using a function called swap, which declares the function swap as void means there is no return value from the function swap. We use pointers in this program which means we can access the values from the function without actually passing the values from the function, please refer to our pointers page to get details about pointers. After getting the values of the pointers into the function swap we interchange the value of pointer 1 to pointer 2 using a temporary variable and their values are automatically changing in the main program. so we just print the new values using printf.

The logic of the program is to declare two variables and read them from the user. Then print the value of the variables before swapping. Then call the function swap(&M, &N) to swap the two numbers. Then display the value of M and N as the value after the swapping.

ALGORITHM

STEP 1:Include the header files to use the built-in header files into the C program.

STEP 2: Declare the variables M and N as type float.

STEP 3: Declare the function void swap(float *ptr1, float  *ptr2 ).

STEP 4: Accept the values of M and N.

STEP 5: Print the values of M and N as Before swapping values.

STEP 6: Call the function swap(&M, &N)  to perform swaps.

STEP 7: Then display the values of M and N as the values after swapping.

Function void swap(float *ptr1, float *ptr2 ) 

STEP 1: Declare a temporary variable temp of type float.

STEP 2: assign temp to *ptr1 ,ptr1=*ptr2 and *ptr2=temp to interchange the contents of the location *ptr1 and *ptr2.

 

 

C Source Code

                                          #include <stdio.h>


void main() {
  float M, N;
  void swap(float * ptr1, float * ptr2); /* Function Declaration */
  printf("Enter the values of M and N\n");
  scanf("%f %f", & M, & N);
  printf("Before Swapping:M = %5.2f\tN = %5.2f\n", M, N); /* printing the values before swapping */
  swap( & M, & N);
  printf("After Swapping:M  = %5.2f\tN = %5.2f\n", M, N); /* display the values after swapping from function */
} /* End of main() */
void swap(float * ptr1, float * ptr2) /* Function swap - to interchanges the contents of two items*/ {
  float temp;
  temp = * ptr1;
  * ptr1 = * ptr2;
  * ptr2 = temp;
} /* End of Function */
                                      

OUTPUT

Enter the values of M and N
32 29

Before Swapping:M = 32.00       N = 29.00

After Swapping:M  = 29.00       N = 32.00