C Program to swap two numbers using temp variable

In this example, we will see C Program to swap two numbers using a temp variable.

C Program to swap two numbers using temp variable

/* C-Program: Read two integer values & swap these values */

#include <stdio.h> 

int main() 
{ 

int a,b,temp; 

printf("Enter the values of a and b:\n"); 
scanf("%d%d", &a,&b); printf("\nbefore swapping:\n"); 

printf("a = %d\tb = %d\n", a,b); 

/* swap logic */ 

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

printf("\nafter swapping:\n"); 

printf("a = %d\tb = %d\n", a,b); 

return 0; 

}

You can see in the above program, firstly we will create two integer variables namely a and b and then take input from the user in a and b.

We will also create a temp variable, then the temp variable is assigned the value of the first variable (a).

Then, the value of the first variable (a) is assigned to the second variable (b).

And then, the temp (which holds the initial value of a) is assigned to second variable(b). This completes the swapping process.

Output :-

Enter the values of a and b:
10 15

before swapping:
a = 10  b = 15

after swapping:
a = 15  b = 10
Related Articles

Leave a Reply