(ii) Write a void function that receives four int parameters: the first two by value and the last two by reference. Name the formal parameters n1, n2, sum and diff. The function should calculate the sum of the two parameters passed by value and then store the result in the first variable passed by reference. It should calculate the difference between the two parameters passed by value and then store the result in the second parameter passed by reference. When calculating the difference, subtract the larger value from the smaller value. Name the function calcSumAndDiff.
#include <iostream>
using namespace std;
void calcSumAndDiff(int, int, int*, int*);
int main() {
int n1=10, n2=5, sum=0, diff=0;
calcSumAndDiff(n1, n2, &sum, &diff);
cout<<"sum: "<<sum<<endl;
cout<<"diff: "<<diff<<endl;
cout<<endl;
return 0;
}
void calcSumAndDiff(int n1, int n2, int *sum, int *diff){
*sum = n1+n2;
if(n1>n2)
*diff = n1-n2;
else
*diff = n2-n1;
}
Comments
Leave a comment