ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to Write a C Program To Swap Two Integers Using Just 2 Variables

Updated on September 25, 2013
C program
C program

How it works

In this C program a user can store two integer values in two variables and the program will swap the two integer values without the help of a third variable

Eg: If a is the first variable and user gives the value 1 to it and a value 2 to b the second variable, in the output it will swap the values, that is sets a=2 and b=1. Its worked out using simple mathematical operations.

Source Code

#include<stdio.h>
void main()
{
    int a,b;
    printf("Enter value of a :");
    scanf("%d",&a);
    printf("Enter value of b :");
    scanf("%d",&b);
     
    a=a+b;
    b=a-b;
    a=a-b;
     
    printf("\nAfter swaping the value of a=%d and b=%d ",a,b);
         
}

Further Explanation

Let 4 and 5 be the values by the user. Now the variable a holds the value 4 and variable b holds the value 5

  • a=a+b (4+5=9) assigns the value 9 to a
  • b=a-b (9-5=4) assigns the value 4 to b
  • a=a-b (9-4=5) assigns the value 5 to a

thus the integer values has been swapped without the help of a third variable.

Was this program easy to understand ?

See results

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      zaheer 3 years ago

      thank u.. the page is very helpful..

      regards

      zaheer ud din

    • Atz profile image
      Author

      Athul M R 3 years ago from Calicut, Kerala, INDIA

      zaheer, positive feedback like this keeps me motivated, thank you =)

    • profile image

      aditi singh 3 years ago

      thnks..

      very easy to understand

      keep doing

      :)

    • profile image

      bfilipek 3 years ago

    • Atz profile image
      Author

      Athul M R 3 years ago from Calicut, Kerala, INDIA

      yup that would be another great method =)

    • profile image

      bethsheba david 2 years ago

      please can you explain a c program to swap two variables with using third variable

    Click to Rate This Article