Adsense 728 * 15

Search

Custom Search

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



Write a C, C++ program to swap two numbers using third variable.

How to Swap Two Numbers using Third Variable.


i) Input two numbers from user. Let's say user has entered two numbers 4 and 5.

     first = 4;
    second = 5;

ii) Declare third variable temp which holds the value.


     Let's assign the value of first in temp.

      temp = first;

     Assign the value of second in first. 

      first = second;

     Assign the value of temp in second.

     second = temp;

Let's write a program to swap two numbers using same logic.

Swap two numbers without using third variable .

C, C++ Interview Questions
     

C Program to Swap Two Numbers using Third Variable

#include<stdio.h>

int main()
{
   int first, second, temp;    

   printf("Enter two numbers");
   scanf("%d%d",&first,&second);

   // Swap logic

   temp = first;
   first = second;
   second = temp;

   printf("Value of first and second after swapping is %d,%d",first,second);
  
   return 0;
   
}



Output:

Enter two numbers :  4   5

Value of first and second after swapping is 5,4

No comments:

Post a Comment