Swap Two Numbers Example in C
On this page (6sections)
About this program
This is an example program in c other programs. Read the concept first: If Else Statement in C, then study the code and output below.
Swap Definition
In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory
Using a temporary variable
The simplest and probably most widely used method to swap two variables is to use a third temporary variable:
temp := x
x := y
y := temp
Swapping Two Numbers Example Program
/*##Swapping Two Numbers*/
/*##Calculation Programs, Datatype Programs, Basic Programs*/
/*##Example*/
#include <stdio.h>
int main()
{
int num1, num2, temp;
printf("Enter the 2 numbers to be swapped : \n");
scanf("%d%d", &num1, &num2);
printf("Before Swapping, the values are : \nnum1 = %d\nnum2 = %d\n",num1,num2);
temp = num1;
num1 = num2;
num2 = temp;
printf("After Swapping, the values are : \nnum1 = %d\nnum2 = %d\n",num1,num2);
return 0;
}
Sample Output:
Enter the 2 numbers to be swapped :
100
99
Before Swapping, the values are :
num1 = 100
num2 = 99
After Swapping, the values are :
num1 = 99
num2 = 100
Related Pages
Learn the concept first, then study the code:
- C Programs — Browse all C Programs.
- If Else Statement in C — Tutorial — decision control for utility programs.
- Reverse Number Example Program In C Programming Language — More in c other programs.
- Example Program for Print 1 to N In C Programming — More in c other programs.