Google Add

Search

C, C++ Program to Swap Two Numbers without using temporary Variable

Write a C, C++ program to swap two numbers without using temporary variable. In this tutorial, You are going to learn how to write a code to swap two numbers without using temporary variable. 

In my previous posts, i have wrote a program to 

Swap two numbers using third variable

Swap two numbers using call by reference method


Logic of Swapping two Numbers without using temporary Variable


i)  Let's assume two variables a and b with a value of 7 and 5;
     a = 7 and b = 5

ii)   Let's swap the numbers. 

       a) a =  a + b ;   // a = 12 ( 7 + 5)

       b)  Now the value of a variable is 12.
        
            b = a - b;  // b = 7 (12 - 5) 

        c) a = a - b;  // a = 5  (12 - 7) 



 After swapping the value of a and b variable is 5 and 7.

C, C++ Interview Questions

C Program to Swap two Numbers without using temporary Variable



#include<stdio.h>

int main()
{
   int a, b; 
   
   printf("Enter two numbers a and b ");
   scanf("%d %d",&a,&b);
   
  // Logic of swapping

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

   printf(" After swapping, a = %d and b = %d",a, b);

   return 0;
}



Output:

Enter two numbers a and b :  7  5

After swapping a = 5 and b = 7


C++ Program to Swap Two Numbers without using Temporary Variable

#include <iostream>
using namespace std;

int main() {
 
   int a, b; 
   
   /* Taking user input. */

   cout << "Enter two numbers a and b ";
   cin  >> a >> b;
   
   /* Swapping logic */

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

   cout<<"After swapping a and b is "<<" "<< a <<" "<< b;

    return 0;
}




No comments:

Post a Comment