Write a C Program to Swap Two Numbers.

Prince Patel
By -
0

Write a C Program to Swap Two Numbers using Three Variable.



In this Article, you will learn how to swap two numbers.

In this C program, takes two integer inputs from the user, performs the swapping operation using a temporary variable, and then displays the swapped values.

Here's a C program to swap two numbers:

#include<stdio.h>
#include<conio.h>

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

    // Input the two numbers from the user
    printf("Enter the first number: ");
    scanf("%d", &num1);

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

    // Display the original numbers
    printf("Original numbers: num1 = %d, num2 = %d\n", num1, num2);

    // Swapping logic using a temporary variable
    temp = num1;
    num1 = num2;
    num2 = temp;

    // Display the swapped numbers
    printf("Swapped numbers: num1 = %d, num2 = %d\n", num1, num2);
}


  • The program starts by declaring three integer variables num1, num2, and temp. num1 and num2 are used to store the two numbers entered by the user, while temp is used as a temporary variable for swapping.
  • The program then prompts the user to input the two numbers using the scanf function.
  • After taking the inputs, the program displays the original values of num1 and num2.
  • The swapping logic is implemented using the temporary variable temp. The value of num1 is stored in temp, then the value of num2 is stored in num1, and finally, the value of temp is stored in num2. This way, the values of num1 and num2 are exchanged or swapped.
  • The program then displays the swapped values of num1 and num2.
Output:

Tags:

Post a Comment

0Comments

Post a Comment (0)