Adsense 728 * 15

Search

Custom Search

Swap Two Numbers without using third Variable - C, C++ Program



Write a C, C++ program to swap two numbers without using temp or third variable. You don't have to use any temporary variable to hold the values.

In my previous posts, i have wrote program to 

Swap two numbers using third variable

Swap two numbers using call by reference method


How to Swap two Numbers without temp or third Variable


i) Take two input numbers from user. Let's say 7 and 5. So the value of first = 7 and second = 5.

ii)   Let's swap the number. 

       a) first =  first + second ;   // first = 12

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

        c) first = first - second;  // first = 12 - 7 = 5



 After swapping the value of first and second variable is 5 and 7.

C, C++ Interview Questions.

C Program to Swap two Numbers without temp or third Variable



#include<stdio.h>

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

   first = first + second;
   second = first - second;
   first = first - second;

   printf(" After swapping first = %d and second = %d",first,second);

   return 0;
}



Output:

Enter two numbers first and second :  7  5

After swapping first = 5 and second = 7


C++ Program to Swap Two Numbers without using Temp or Third Variable

#include <iostream>
using namespace std;

int main() {
 
   int first, second; 
   
   /* Taking user input. */

   cout << "Enter first and second numbers ";
   cin >>first>>second;
   
   /* Swap the values. */

   first = first + second;
   second = first - second;
   first = first - second;

   cout<<"After swapping first and second number is"<<" "<<first<<" "<<second;

    return 0;
}

PHP Code to swap two numbers without using temp

No comments:

Post a Comment