Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using C/C++, declare three integer variables (e.g. A,B,C) in main() and assign t

ID: 3674671 • Letter: U

Question

Using C/C++, declare three integer variables (e.g. A,B,C) in main() and assign their values from standard input (cin).Then, call a function swap 1() to swap their values through pointers (e.g. A,B,C are 4,5, and 6, after calling swap(),A has B's value 5, B has C's value 6, and C has A's value 4), and output A,B, and C; finally, define another function swap2 to swap A,B,C one more time using references.

Note: to swap A, B, C by pointers; the swap function needs to have three pointer arguments which are initialized with the address of A, B, C defined above.

Explanation / Answer

#include <iostream>
using namespace std;

// swap function using pointer
void swapUsingPointer(int *a, int *b, int *c){
   int temp = *a; // storing value of 'a' in temp;
   *a = *b; // assiging value of b to a
   *b = *c; // value of b to c
   *c = temp; // value of a to c
   }
  
//swap function using refrence
void swapUsingRefrence(int &a, int &b, int &c){
   int temp = a; // storing value of 'a' in temp;
   a = b; // assiging value of b to a
   b = c; // value of b to c
   c = temp; // value of a to c
   }
int main() {
  
int a, b, c;
cout<<"Enter value of A, B and C"<<endl;
cin>>a>>b>>c;
  
//swap using pointer
swapUsingPointer(&a,&b,&c);
cout<<"Value of A, B, C after swapping: "<<a<<" "<<b<<" "<<c<<endl;
  
//swap using pointer
swapUsingRefrence(a,b,c);
cout<<"Value of A, B, C after swapping: "<<a<<" "<<b<<" "<<c<<endl;
return 0;

}

/*

Output:

Enter value of A, B and C
1
2
3
Value of A, B, C after swapping: 2 3 1
Value of A, B, C after swapping: 3 1 2

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote