This function is suppose to return 55 but every time I run it it says "The sum is 0". I have tried switching out the values in the void function, switching the loop to a for loop, and using return void () but nothing I do change the sum value. What am I doing wrong?
void compute_sum(int limit)
{
int sum = 0;
int number = 1;
while (number <= limit)
{
sum += number;
number++;
}
}
int main()
{
int sum = 0;
int limit = 10;
compute_sum(limit);
cout << "The sum is " << sum << endl;
return 0;
}
Also you cannot use return 0; in a void function. it does not return a value.
- Look again.
@alyssnyx
The problem is that in your compute_sum() function, you have a local variable named int sum, which is what ends up getting modified.
Then in main(), you have a variable with the same identifier and type, which you've initialized to zero, but never modify.
Fix this by either:
1.) As sky3 said, modify the function to return the sum.
2.)passing sum from main() by reference to compute_sum() and removing line 3.
#include <iostream>
usingnamespace std;
int compute_sum(int number, int sum)
{
sum = 0;
number = 1;
int limit=10;
while (number <= limit)
{
sum = sum+ number;
number++;
}
return sum;
}
int main()
{
int sum = 0;
int number = 1;
int limit=10;
cout << compute_sum(number,sum);
return 0;
}
You don't need that extra int sum parameter if you're returning the sum from the function. You really only need to make a few changes to the original code:
int compute_sum(int limit) // 'void' --> 'int'
{
int sum = 0;
int number = 1;
while (number <= limit)
{
sum += number;
number++;
}
return sum; // Return the sum here
}
int main()
{
int sum = 0;
int limit = 10;
sum = compute_sum(limit); // Assign the return value to 'sum'
cout << "The sum is " << sum << endl;
return 0;
}
// Fun with pointers
#include <iostream>
usingnamespace std;
void compute_sum (int limit, int *psum)
{
int sum = 0;
int number = 1;
while (number <= limit)
{
sum = sum+ number;
number++;
}
*psum = sum;
}
int main ()
{
int number = 10;
int *a;
compute_sum (number, a);
cout << *a;
return 0;
}
Thanks for all the help! After reading the replies, switching the void to int seems to be simpler. Garion thanks for that pointer tip, I would use it but we haven't got to learn about that yet . Again thanks everyone for the help, I was stuck on this for hours.