Followers

Sunday, April 9, 2023

Program To Swap Two Numbers

Program:

 #include <iostream>  
 using namespace std;  
 void swap(int &num1, int &num2){  
      int temp;  
      temp = num1;  
      num1 = num2;  
      num2 = temp;  
 }  
 int main(){  
      int num1, num2;  
      cout<<"Enter the value of num 1: ";  
      cin>>num1;  
      cout<<"Enter the value of num 2: ";  
      cin>>num2;  
      cout<<"Before Swap: "<<endl;  
      cout<<"num1 = "<<num1<<endl;  
      cout<<"num2 = "<<num2<<endl;  
      swap(num1, num2);  
      cout<<"After Swap: "<<endl;  
      cout<<"num1 = "<<num1<<endl;  
      cout<<"num2 = "<<num2<<endl;       
      return 0;  
 }  
Output:


Working of the Program:
  1. The program starts by including the iostream library, which provides basic input and output functionalities in C++.

  2. A swap function is defined that takes two integer parameters num1 and num2 by reference. The function swaps the values of num1 and num2 using a temporary variable temp.

  3. The main function is defined, which declares two integer variables num1 and num2 to store the user inputs.

  4. The cout statement is used to prompt the user to enter the value of num1.

  5. The cin statement is used to read the value of num1 entered by the user from the console.

  6. The cout statement is used to prompt the user to enter the value of num2.

  7. The cin statement is used to read the value of num2 entered by the user from the console.

  8. The values of num1 and num2 before the swap operation are printed on the console using the cout statement.

  9. The swap function is called with the input values of num1 and num2 to swap their values.

  10. After the swap operation, the values of num1 and num2 are printed on the console using the cout statement.

  11. The return 0 statement is used to terminate the program.

Overall, this is a simple program that demonstrates the use of functions and passing parameters by reference in C++.

No comments:

Post a Comment

Program to Find the Length of a String

Program: #include <iostream> using namespace std; int main() { string a; cout<<"Enter the string...