Consider the following function void doItint a int b a a

Consider the following function: void doIt(int& a, int b) { a = a * 2; b = b * 2 } Write a main program that prompts the user for two integer numbers (num1 and num2). Then, the main program calls the function doIt with num1 and num2 as parameters. The main program will finally print the content of num1 and num2 on the screen. Explain what is the difference between a and b results.

Solution

#include <iostream>
using namespace std;

void doit(int &a,int b)
{
a = a*2;
b = b*2;
}

int main() {
   // your code goes here
   int num1,num2;
  
   cout << \"Input integer 1 : \";
   cin >> num1;
  
   cout << \"Input integer 2 : \";
   cin >> num2;
  
   doit(num1,num2);
  
   cout << \"Value of integer 1 : \" << num1 << endl;
   cout << \"Value of integer 2 : \" << num2 << endl;
  
   return 0;
}

OUTPUT:

Input integer 1 : 5

Input integer 2 : 5

Value of integer 1 : 10
Value of integer 2 : 5

The difference between a & b result is a value got doubled while b value remain the same this happened because a was passed by reference which b was passed by value to the function doit.

Consider the following function: void doIt(int& a, int b) { a = a * 2; b = b * 2 } Write a main program that prompts the user for two integer numbers (num1

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site