0

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;
}
3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by csurfer
0

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);
}
0

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.

Edited by csurfer: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.