Write a C program of swapping values of three Variables without using forth variable

Write a simple program in the C programming language to swap the numbers of three variables without using the forth variable. Make a C program by taking three variables only of integer type.  The value of a will be swapped to b, and b’s value will be swapped to c and c to a. The code of the C program is as follows –

/* Write a simple C program to swap the values of three
variables without taking the forth varaible */
#include<stdio.h>
void main()
{
     int a,b,c;
     printf(" Enter values of a, b and c \n");
     scanf("%d %d %d",&a,&b,&c);

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

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

     printf("\n After swapping their values are as below -");
     printf("\n a = %d",a);
     printf("\n b = %d",b);
     printf("\n c = %d",c);
     getch();
}

Input
a = 14
b = 45
c = 12

Processing
a = a + b + c;
a = 14 + 45 + 12 = 71;
a = 71;

b = a – b – c;
b = 71 – 45 – 12 = 14
b = 14;

c = a – b -c;
c = 71 – 14 – 12;
c = 45;

a = a – b – c;
a = 71 – 14 – 45 = 12;
a = 12;

Output
a = 12;
b = 14;
c = 45;

yashan has written 70 articles

8 thoughts on “Write a C program of swapping values of three Variables without using forth variable

Cancel reply

Leave a Reply to harsha

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>