Swaps the values of two variables in c programming

Swap the Values of Two Variables in C

How to Swap the Values of Two Variables in C

Swapping the values of two variables is a basic programming task that helps in understanding the concept of temporary storage and variable assignment. Below is a simple C program that demonstrates how to swap the values of two variables.

Example Program

#include <stdio.h>

int main() {
    int a, b, temp;

    // Initialize variables
    a = 5;
    b = 10;

    // Print original values
    printf("Before swapping:\\n");
    printf("a = %d, b = %d\\n", a, b);

    // Swap the values
    temp = a;
    a = b;
    b = temp;

    // Print swapped values
    printf("After swapping:\\n");
    printf("a = %d, b = %d\\n", a, b);

    return 0;
}

Explanation

This program uses a temporary variable to swap the values of a and b. The key steps are:

  • Initialization: Variables a and b are initialized with values 5 and 10, respectively.
  • Printing Original Values: The initial values of a and b are printed.
  • Swapping: A temporary variable temp is used to hold the value of a while a is assigned the value of b. Then, b is assigned the value stored in temp.
  • Printing Swapped Values: The values of a and b after swapping are printed.

Output

When you run this program, it will display:

Before swapping:
a = 5, b = 10
After swapping:
a = 10, b = 5
Note: This method of swapping is straightforward and uses an additional variable to temporarily hold one of the values. It's a common technique for beginners to understand how variables can be reassigned.

Comments

Popular Posts