Easy Tutorial
❮ C Standard Library Signal H C Pointer To An Array ❯

C Language Example - Swapping Values of Two Numbers

C Language Examples

Using a Temporary Variable

The following example demonstrates how to swap the values of two floating-point numbers.

Example

#include <stdio.h>

int main()
{
    double firstNumber, secondNumber, temporaryVariable;

    printf("Enter the first number: ");
    scanf("%lf", &firstNumber);

    printf("Enter the second number: ");
    scanf("%lf", &secondNumber);

    // Assign the value of the first number to temporaryVariable
    temporaryVariable = firstNumber;

    // Assign the value of the second number to firstNumber
    firstNumber = secondNumber;

    // Assign the value of temporaryVariable to secondNumber
    secondNumber = temporaryVariable;

    printf("\nAfter swapping, firstNumber = %.2lf\n", firstNumber);
    printf("After swapping, secondNumber = %.2lf", secondNumber);

    return 0;
}

Execution Result:

Enter the first number: 1
Enter the second number: 2

After swapping, firstNumber = 2.00
After swapping, secondNumber = 1.00

Without Using a Temporary Variable

Swapping the values of two integers without using a temporary variable:

Example

#include <stdio.h>

int main() {
    int a, b;

    a = 11;
    b = 99;

    printf("Before swapping - \n a = %d, b = %d \n\n", a, b);

    a = a + b;  // (11 + 99 = 110) Now a contains the sum of both, b is unchanged
    b = a - b;  // (110 - 99 = 11)
    a = a - b;  // (110 - 11 = 99)

    printf("After swapping - \n a = %d, b = %d \n", a, b);
}

Execution Result:

Before swapping - 
 a = 11, b = 99 

After swapping - 
 a = 99, b = 11

C Language Examples

❮ C Standard Library Signal H C Pointer To An Array ❯