#include <stdio.h>
int main()
{
// Declare variables to store the two numbers
int num1, num2, temp;
// Ask the user for input
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
// Display numbers before swapping
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
// Swap the numbers
temp = num1; // Store num1 in a temporary variable
num1 = num2; // Assign the value of num2 to num1
num2 = temp; // Assign the value of temp (original num1) to num2
// Display numbers after swapping
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
Explanation
return 0;
: This indicates that the program finished successfully and is returning an exit status of 0
.
#include <stdio.h>
:
This line includes the standard input-output library, allowing us to use functions for input and output, like printf
and scanf
.
int main()
:
This defines the main function, where the program starts executing. The int
indicates that this function will return an integer value.
Variable Declaration:
int num1, num2, temp;
: Here, we declare three integer variables: num1
and num2
for storing the user inputs, and temp
for temporarily holding one of the values during the swap.
Input from the User:
printf("Enter the first number: ");
: This prompts the user to enter the first number.
scanf("%d", &num1);
: This reads the integer input and stores it in num1
.
The same two lines are repeated for the second number, storing it in num2
.
Displaying Values Before Swapping:
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
: This line prints the values of num1
and num2
before they are swapped.
Swapping the Numbers:
temp = num1;
: The value of num1
is stored in the temporary variable temp
.
num1 = num2;
: The value of num2
is assigned to num1
.
num2 = temp;
: The original value of num1
(stored in temp
) is assigned to num2
.
Displaying Values After Swapping:
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
: This prints the new values of num1
and num2
after swapping.
Return Statement:
return 0;
: This indicates that the program finished successfully and is returning an exit status of 0
.
OUTPUT
Enter two numbers:
5 10
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5