C Program to Swap Two Numbers

In C programming, it is often necessary to swap the values of two variables. In this program, we will write a C program that prompts the user to enter two numbers, swaps their values, and prints the new values.

Problem Statement

The problem statement is to write a C program that prompts the user to enter two numbers, swaps their values, and prints the new values.

Solution

Here is the C program to swap two numbers:

#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);

    temp = num1;
    num1 = num2;
    num2 = temp;

    printf("After swapping, the first number is %d and the second number is %d\n", num1, num2);

    return 0;
}

Output

Explanation

First, we include the stdio.h header file which is used for input and output functions. Then, we define the main() function as the starting point of our program.

We declare three integer variables – num1, num2, and temp. num1 and num2 are used to store the two numbers entered by the user, and temp is used to temporarily store the value of num1 while swapping the values.

Next, we prompt the user to enter the first number using the printf() function. The scanf() function is used to read in the first number entered by the user. The format specifier %d is used to specify that the input should be read as an integer.

We then prompt the user to enter the second number using the printf() function. The scanf() function is used again to read in the second number entered by the user.

We then use the temp variable to temporarily store the value of num1. We assign num2 to num1 and temp to num2. This effectively swaps the values of num1 and num2.

Finally, we print the result using the printf() function. We use the format specifier %d to print the values of num1 and num2 after they have been swapped.

Conclusion

In this tutorial, we learned how to write a C program to swap two numbers. We used a temporary variable temp to store the value of one of the variables while swapping their values. We also used the printf() function to print the result to the console.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...