Pass by reference help

Write your question here.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  // PartialSum.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;

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

int main()
{
    unsigned int i = getValidPositiveInteger();
    unsigned int n = getValidPositiveInteger();
    cout << "Enter the number of terms in the partial sum approximation of the series (n): \n";
    cin >> i;
    cout << "Using pass by value, the partial term using " << i << " terms is: \n" << sum2(i);
    cout << "Using pass by reference, the partial term using " << i << " terms is: \n" << sum1(n, another parameter here);
    system("PAUSE\n");
    return 0;
}

void sum1(double &sum, unsigned int n)
{

    sum = sum2(n);

}

double sum2(unsigned int n)
{
    double sum = 0, result;
    unsigned int a;
    for (a = 1; a <= n; ++a)
    {
        result = pow((1.0 / a), 2);
        sum += result;
    }
    return (sum);
}

// 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;
}


I'm trying to pass two parameters into the function sum1, I have n but the second one, sum doesn't work, I tried changing the unsigned int n = getPositiveInteger() to a double, but that doesn't work either, if anyone could help me out, that would be so appreciated, thanks.
I wasn't sure what your trying to do, no comments in code, sum, sum1, sum2 all overlap, too confusing.

I stripped down your code to show how it's supposed to work. Hopefully that helps

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

double sum(double sum, int n)
{
	cout << "1st " << sum  << " 2nd " << n << endl;
return sum+n;	
}

int main()
{
	double n=5; 
	int i=6;

	cout << "Using pass by reference, the partial term using " << i << " terms is: " << sum(n, i);
	return 0;
}
Last edited on
Topic archived. No new replies allowed.