I am trying to learn parameters by reference. In my code i try to compute the sum between 1 and n. This is what i got so far and if i input 5 it outputs a extremely high number. Any suggestions?

#include <iostream>
#include <cmath>
using namespace std;

void sum(int& n){
for (int i(1), result(0), n; i<=n ; i++){
result += i;
}
return;
}

int main(){
int result, n;
cin >> n;
sum(n);
cout << result << endl;

system("PAUSE");
return 0;
}

Recommended Answers

All 2 Replies

what exactly are you trying to do? if you want to compute sum by sum.

remember that when you get a parameter as a reference using the & ampersand operator. then you don't have to computer with for loops and stuff.

int sum(int *n)
{
return 1 + *(n);
}

Problems :
1)The result in your sum function and the result in your main function are different as you are not at all passing the variable result to the sum function.So pass result variable also along with n to the sum function as

sum(n,result); // Make sure result is set to 0 before you make this call and change the prototype of function sum accordingly

2)Doing something like

for(int i(0),result,n;i<=n;i++)

tries to declare variables result and n again which is actually not required.Only this

for(int i(1);i<=n;i++)

suffices.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.