Can someone explain me pass by reference please

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  #include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <cmath>

using namespace std;


void sum1(double&, unsigned int);
unsigned int getValidPositiveInteger();

int main()
{
	unsigned int 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, unsigned int n)
{

}


// Get a valid integer from the user
unsigned int 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace 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.

There are plenty of videos that explain this, if you are like me, and learn by watching. Take this for example - https://www.youtube.com/watch?v=wAmq8eIkdI8
Last edited on
Topic archived. No new replies allowed.