Write a C Program to Swap Two Numbers

Write a C Program to Swap Two Numbers

Swapping two numbers is a common programming task that involves exchanging the values of two variables. In this example, we’ll create a C program to swap two numbers using a temporary variable.

Program :

#include <stdio.h>

#include <conio.h>

int main(){

    int a, b, c;

    printf("Enter two numbers \n");

    scanf("%d %d", &a, &b);

    printf("\na:%d\n b:%d\n",a,b);   

    c = a;

    a = b;

    b = c;

    printf("\nAfter Swap\n");

    printf("\na:%d\n b:%d\n",a,b);

    getch();

    return 0;

}

Explanation:

  • Include Header: #include <stdio.h> is used to include the standard input-output header file.
  • Declare Variables: int a, b, c; declares three integer variables a, b, and c.
  • Input values for a and b: scanf is used to take user input for the values of a and b.
  • Swapping using a third variable: The values of a and b are swapped using a temporary variable c.
  • Output the swapped values: The program then prints the swapped values of a and b to the console.

Output:

Enter two numbers

6 7

a:6

 b:7

After Swap

a:7

 b:6 

Conclusion:

This C program demonstrates a simple and common algorithm for swapping two numbers. Understanding such basic operations is essential for building a foundation in programming. The use of a temporary variable is a straightforward approach, and it ensures that the values are swapped without losing any data.

Scroll to Top