English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Control Structures

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Other

C Language Reference Manual

C Program to Swap Two Numbers

Comprehensive Collection of C Programming Examples

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

To understand this example, you should be familiar with the followingC ProgrammingTopic:

swap numbers using a temporary variable

#include <stdio.h>
int main() {
      double first, second, temp;
      printf("Enter the first number: ");
      scanf("%lf", &first);
      printf("Enter the second number: ");
      scanf("%lf", &second);
      //The value of first is assigned to temp
      temp = first;
      // The value of second is assigned to first
      first = second;
      // The value of temp (the initial value of first) is assigned to second
      second = temp;
      printf("\nAfter swapping, firstNumber = %.0lf", first);2lf\n", first);
      printf("After swapping, secondNumber = %.0lf", second);2lf, second);
      return 0;
}

Output Result

Enter the first number: 56.5
Enter the second number: 45.8
After swapping, firstNumber = 45.80
After swapping, secondNumber = 56.50

In the above program, the value of the first variable is assigned to the temp variable.

Then, the value of the first variable is assigned to the second variable.

Finally, temp (which retains the initial value of first) is assigned to second. This completes the swapping process.

swap numbers without using a temporary variable

#include <stdio.h>
int main() {
    double a, b;
    printf("Enter a: ");
    scanf("%lf", &a);
    printf("Enter b: ");
    scanf("%lf", &b);
    // swap
    // 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("After swap, a = %.0lf\n", a);2lf\n", a);
    printf("After swap, b = %.0lf);2lf", b);
    return 0;
}

Output Result

Enter a: 10.25
Enter b: -12.5
After swap, a = -12.50
After swap, b = 10.25

Comprehensive Collection of C Programming Examples