Cover Image for Swap Number in C
105 views

Swap Number in C

To swap two numbers in C, you can use a temporary variable to store one of the numbers temporarily. Here’s a C program that demonstrates how to swap two numbers:

C
#include <stdio.h>

int main() {
    int num1, num2, temp;

    printf("Enter the first number: ");
    scanf("%d", &num1);

    printf("Enter the second number: ");
    scanf("%d", &num2);

    printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

    // Swap the numbers
    temp = num1;
    num1 = num2;
    num2 = temp;

    printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);

    return 0;
}

In this program:

  1. We input two integers, num1 and num2, from the user.
  2. We print the values of num1 and num2 before swapping.
  3. We use a temporary variable temp to store the value of num1 temporarily.
  4. We then assign the value of num2 to num1 and finally assign the value stored in temp (which was the original value of num1) to num2. This effectively swaps the values of the two variables.
  5. We print the values of num1 and num2 after swapping, showing that they have been swapped.

Compile and run the program, and you can enter two numbers to see them swapped.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS