C program to swap two numbers

C program to swap two numbers

This C program is to swap two numbers or exchange two numbers.For example if we have two numbers let us say a=7 and b=8,then on swapping we get a=8 and b=7.This a very simple and basic c program.

Logic

Just take a temporary variable and store the 1st value in it and then in variable a store the value of 2nd variable(b).

Then store the value of temp variable in 2nd variable.There you go you performed swapped operation successfully.

Dry Run of the Program

Let us take a=7 and b=8.

t=a  i.e. t=7

a=b i.e. a=8

b=t i.e. b=7

Now we get a=8 and b=7 , hence the numbers have been swapped.

Program

#include<stdio.h>
void main()
{
	int a,b,t;

  	printf("Enter the two numbers\n");
	scanf("%d%d",&a,&b);
	printf("The values before swap\n");
	printf("a=%d\tb=%d\n",a,b);
	t=a;
	a=b;
	b=t;
	printf("The values after swap\n");
    printf("a=%d\tb=%d\n",a,b);
 }

Output

Share Me!