Swapping two numbers

Swapping two numbers

Swapping two numbers

In this example, you will learn to swap two numbers in C programming using two different techniques.

Swap Numbers Using Temporary Variable

#include<stdio.h>
#include<conio.h>
void main() {
      double first, second, temp;
printf("\n\t\t\t...Welcome To EduNews.Tech... ");

      printf("\n\nEnter first number: ");
      scanf("%lf", &first);
      printf("Enter second number: ");
      scanf("%lf", &second);

      // Value of first is assigned to temp
      temp = first;

      // Value of second is assigned to first
      first = second;

      // Value of temp (initial value of first) is assigned to second
      second = temp;

      printf("\nAfter swapping, firstNumber = %.2lf\n", first);
      printf("After swapping, secondNumber = %.2lf", second);
printf("\n\n\n\t\t\tThankyou for Joining Us !");
printf("\n\t\t\t!Regards EduNews !");

      getch();
}

Program Output:

swaping two numbers

In the above program, the temp variable is assigned the value of the first variable.
Then, the value of the first variable is assigned to the second variable.
Finally, the temp (which holds the initial value of first) is assigned to second. This completes the swapping process.

Swap Numbers Without Using Temporary Variables

#include <stdio.h>
#include<conio.h>
void main() {
    double a, b;
printf("\n\t\t\t...Welcome To EduNews.Tech... ");

    printf("\n\nEnter value of a: ");
    scanf("%lf", &a);
    printf("Enter value of b: ");
    scanf("%lf", &b);

    // Swapping

    // a = (initial_a - initial_b)
    a = a - b;   
 
    // b = (initial_a - initial_b) + initial_b = initial_a
    b = a + b;

    // a = initial_a - (initial_a - initial_b) = initial_b
    a = b - a;

    printf("\nAfter swapping, a = %.2lf\n", a);
    printf("After swapping, b = %.2lf", b);
printf("\n\n\n\t\t\tThankyou for Joining Us !");
printf("\n\t\t\t!Regards EduNews !");

    getch();
}

Program Output:

swaping two numbers1

I hope this post helps you to understand the “Swapping of two Numbers” with two different techniques and its implementation in C programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *