C Program: Swap Two Numbers

Swapping of two numbers is one of the many classic programming examples given in the original text on the subject, The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie (Chap. 4, 'Functions and Program Structure').

There's more than one way to go about writing a program to swap or interchange the values of two given numbers in C. However, to begin with, we will explore only a couple of programs using simple assignment and arithmetic operators and keep the use of bitwise XOR operator and pointers for a different page.

c program swap numbers

In our first program below, we will be making use of a temporary (or third) variable called temp. When you run the program and input the first number as 2 and the second number as 3, the program will swap their values and their resulting values will be interchanged. The first number will become 3 and the second number will become 2.

				
				#include <stdio.h>

				int main() {
					int a, b, temp;

				    printf("Enter the first number: ");
				    scanf("%d", &a);

				    printf("Enter the second number: ");
				    scanf("%d", &b);

				    temp = a;
				    a = b;
				    b = temp;

				    printf("The value of the first number is %d", a);
				    printf("\n");
				    printf("The value of the second number is %d", b);
				    printf("\n");

					return 0;
				}
				
			

Without temp

We can also achieve the same without the use of temporary variable.

					
					#include <stdio.h>

					int main() {
						int a, b;

					    printf("Enter the first number: ");
					    scanf("%d", &a);

					    printf("Enter the second number: ");
					    scanf("%d", &b);

					    a = a + b;
					    b = a - b;
					    a = a - b;

					    printf("The value of the first number is %d", a);
					    printf("\n");
					    printf("The value of the second number is %d", b);
					    printf("\n");

						return 0;
					}