Write a C Program to Swap Two Numbers
Swapping two numbers is a common programming task that involves exchanging the values of two variables. In this example, we’ll create a C program to swap two numbers using a temporary variable.
Program :
#include <stdio.h> #include <conio.h> int main(){ Â Â Â int a, b, c; Â Â Â printf("Enter two numbers \n"); Â Â Â scanf("%d %d", &a, &b); Â Â Â printf("\na:%d\n b:%d\n",a,b);Â Â Â Â Â Â c = a; Â Â Â a = b; Â Â Â b = c; Â Â Â printf("\nAfter Swap\n"); Â Â Â printf("\na:%d\n b:%d\n",a,b); Â Â Â getch(); Â Â Â return 0; }
Explanation:
- Include Header: #include <stdio.h> is used to include the standard input-output header file.
- Declare Variables: int a, b, c; declares three integer variables a, b, and c.
- Input values for a and b: scanf is used to take user input for the values of a and b.
- Swapping using a third variable: The values of a and b are swapped using a temporary variable c.
- Output the swapped values: The program then prints the swapped values of a and b to the console.
Output:
Enter two numbers 6 7 a:6 Â b:7 After Swap a:7 b:6
Conclusion:
This C program demonstrates a simple and common algorithm for swapping two numbers. Understanding such basic operations is essential for building a foundation in programming. The use of a temporary variable is a straightforward approach, and it ensures that the values are swapped without losing any data.