Write a program in C++ to swap two numbers.
Swapping:
Swapping in computer science means shuffling or interchanging. Mutually exchanging two values is called swapping.
Using a temporary variable :
The simplest method to swap two variables is to use a third temporary variable. The temporary variable is used to keep the value of one of the variables temporarily. The values in variables may be a numeric or alphabetic or any other characters I.e. alphanumeric, symbols etc. Temporary variable is a third variable along with two other variables carrying values. Temporary variable is empty but initialized at declaration and no value is assigned. The value is assigned at the time of shuffling of variables. For this , the value of one variable carrying values is assigned to the temporary variable thus that variable becomes empty. Now the value of the other value variable is assigned to the first recently emptied variable. At the end the value of the temporary variable is assigned to the second variable. Now the temporary variable is again empty and both the numbers are swapped. The same is shown in figure.
Pseudo code:
Here is the pseudo code for swapping two numbers.
define swap(x, y)
temp := x
x := y
y := temp
Sample Solution :-
C++ Code :
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Swap two numbers :\n";
cout << "-----------------------\n";
int num1, num2, temp;
cout << " Input 1st number : ";
cin >> num1 ;
cout << " Input 2nd number : ";
cin >> num2;
temp=num2;
num2=num1;
num1=temp;
cout << " After swapping the 1st number is : "<< num1 <<"\n" ;
cout << " After swapping the 2nd number is : "<< num2 <<"\n\n" ;
}
Sample Output:
Swap two numbers:
Input 1st number : 35
Input 2nd number : 29
After swapping, the 1st number is : 29
After swapping, the 2nd number is : 35
Flowchart:
Here is the flowchart for swapping numbers:
No comments:
Post a Comment