In this tutorial you will learn about the C Program to Swap Two Numbers and its application with practical example.
In this tutorial, we will learn to create a program to swap two numbers in C programming language.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- C Data Types
- C Variables
- C Input Output
- C Operators
Program to Swap Two Numbers
In this program we will swap two integer numbers entered by the user. We would first declared and initialized the required variables. Next, we would prompt user to input two integer numbers. Later in the program we will swap numbers using a temporary variable. Finally, we will display number values after swapping of numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<stdio.h> int main() { int num1, num2, temp; printf("Enter first number: "); scanf("%d", &num1); printf("Enter second number: "); scanf("%d", &num2); // Value of num1 is assigned to temp temp = num1; // Value of num2 is assigned to num1 num1 = num2; // Value of temp is assigned to num2 num2 = temp; printf("\nAfter swapping, first number = %d\n", num1); printf("After swapping, second number = %d", num2); return 0; } |
Output:-
In the above program, we have first declared and initialized a set variables required in the program.
- num1 = it holds the first integer number value
- num2 = it holds the second integer number value
- temp = it is used to hold temporary value
In the next statement user will be prompted to enter the two integer number values which will be assigned to variable ‘num1’ and ‘num2’ respectively. Next, we will swap two integer numbers using a temporary variable. Finally, we will display number values after swapping of numbers.