Hello. I need someone to explain me how to write this code by using pass by reference. I managed to understand how to do it through pass by value but the pass by reference is confusing me.
The goal here is to find the convergent sum of (1/n)^2 aka: (1/1)^2 + (1/2)^2 +... (1/n)^2.
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <cmath>
usingnamespace std;
void sum1(double&, unsignedint);
unsignedint getValidPositiveInteger();
int main()
{
unsignedint i = getValidPositiveInteger();
cout << "Enter the number of terms in the partial sum approximation of the series (n): \n";
cin >> i;
cout << "Using pass by reference, the partial term using " << i << " terms is: " << sum1(???);
return 0;
}
void sum1(double& sum, unsignedint n)
{
}
// Get a valid integer from the user
unsignedint getValidPositiveInteger() {
int userInput;
cin >> userInput;
while (cin.fail() || userInput < 0) {
cin.clear();
cin.ignore();
cout << "Please enter a positive integer only\n";
cin >> userInput;
}
return userInput;
}
Pass by value just copies the variables passed in. While pass by refence doesnt copy, it gets the original variables. Which allows you to do something like this.
#include <iostream>
usingnamespace std;
void changeNumbers(int& a, int& b)
{
a = 10;
b = 25;
}
int main()
{
int a = 5;
int b = 6;
changeNumbers(a, b);
std::cout << a << " " << b << endl;
}
This prints out 10 and 25, because the function changed the original variables int a and int b, which were created in main. If I were to pass them by value, the function would recieve copies, and those copies would be equal to 10 and 25, while the original ones remain 5 and 6, so it would print out 5 and 6.