Hi guys, so I'm having a bit of trouble with this code. The purpose of this code is to try and calculate the sum of the integers 1-10 (inclusive). The answer SHOULD be 55, but I keep getting 0 and I'm not sure why/how I can fix the code so that it calculates it correctly. I'm new to C++ and have no clue on void functions/parameters. If anyone could explain it would
mean a lot. Thanks!
Edit: Btw, I did compile, link, run, etc. There are no compiling errors. It just says that "The sum is 0".
EDITx2:
I do know that the sum of the numbers aren't displaying correctly inside the main function and so I need to adjust the code so that main "calls" the function and then it should be able to display the sum correctly, right? I'm having trouble with that portion of it.
Oh and a few requirements I had in working on this is that I'm not supposed to use global variables or calculate anything inside the main function itself.
#include <iostream>
usingnamespace std;
void compute_sum(int);
int main()
{
int sum = 0;
int b = 10;
compute_sum(b);
cout << "The sum is " << sum << endl;
return 0;
}
void compute_sum(int x)
{
int sum = 0;
int num = 1;
while (num <= x)
{
sum += num;
num++;
}
}
It's still not working. I didn't really understand the tutorial, but I tried returning the value like they did in the example except the value didn't change and I got an error saying:
"error: return-statement with a value, in function returning 'void' [-fpermissive]"
Would you be able to show it by any chance?
EDIT:
I do know that the sum of the numbers aren't displaying correctly inside the main function and so I need to adjust the code so that main "calls" the function and then it should be able to display the sum correctly, right?
Oh and a few requirements I had in working on this is that I'm not supposed to use global variables or calculate anything inside the main function itself.
#include <iostream>
usingnamespace std;
int compute_sum(int);
int main()
{
int sum = 0;
int b = 10;
sum = compute_sum(b);
cout << "The sum is " << sum << endl;
return 0;
}
int compute_sum(int x)
{
int sum = 0;
int num = 1;
while (num <= x)
{ sum += num;
num++;
}
return sum;
}