Written by Sai Sameera Thota on January 8, 2013 in C > Programming

C Program to Swap two Numbers

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Swapping is a method of exchanging values. In the first method we will be using three variables: a, b, temp. User will enter two values into the variables and then swapping will take place by using the third variable. In the second method we will be swapping two numbers without using third variable.

Ex:
#1. a=3, b=5.
temp = a => 3.
a = b => 5.
b = temp => 3.

So a=5, b=3.

#2. a=3, b=5.
a = a+b = 3+5 = 8.
b = a-b = 8-5 = 3.
a = a-b = 8-3 = 5.

So a=5, b=3.
Swapping Two Numbers using Third Variable:

#include<stdio.h>
#include<conio.h>
void main()
{
      int a,b,temp;
      clrscr();
      printf("Enter the value of a : ");
      scanf("%d",&a);
      printf("Enter the value of b : ");
      scanf("%d",&b);
      printf("Values before swapping are a = %d and b = %d\n",a,b);
      temp = a;
      a = b;
      b = temp;
      printf("Values after swapping are a = %d and b = %d",a,b);
      getch();
}

Swapping two numbers without using Third variable

#include<stdio.h>
#include<conio.h>
void main()
{
      int a,b;
      clrscr();
      printf("Enter the value of a : ");
      scanf("%d",&a);
      printf("Enter the value of b : ");
      scanf("%d",&b);
      printf("Values before swapping are a = %d and b = %d\n",a,b);
      a=a+b;
      b=a-b;
      a=a-b;
      printf("Values after swapping are a = %d and b = %d",a,b);
      getch();
}

Output:
Swapping-using-C

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: