# Thread: A VERY simple program is confusing me..HELP PLEASE!

1. ## A VERY simple program is confusing me..HELP PLEASE!

I am now in my first C++ class, and I am learning it fairly well, but it seems like the simplest programs are giving me the most trouble.
This program uses the function FindSum() , and tells the user to input positive integers (negative integer to quit), and then adds all of the positive integers together as one positive output sum. I know some of you guys are probably laughing at me right now, I know it is a simple program, but I just can't get it to output the correct numbers.

Here is what I have so far, please feel free to run it yourself and let me know what I am doing wrong. Thanks! Brent

#include <iostream>
using namespace std;
int FindSum(int, int);
int main ()
{
int a, b;
cout << "Enter a positive value (negative value to stop): ";
cin >> a;
b=FindSum(a,b);
cout << "Your numbers added is: "<<b<< endl;
return 0;
}

FindSum(int x, int y)
{ while (x > 0){
cin>>x;
y=x+y;}
return y ;
}

2. I don't know if this is the problem but why are you passing b to FindSum? It hasn't been initialized, it's just junk...

Also, the while loop is messed up. It will ask for a number then add it to y before checking if it's > 0. Put cin >> x; after y=x+y;. This code should work:

#include <iostream>
using namespace std;
int FindSum(int);
int main ()
{
int a, b;
cout << "Enter a positive value (negative value to stop): ";
cin >> a;
b=FindSum(a);
cout << "Your numbers added is: "<<b<< endl;
return 0;
}

FindSum(int x)
{
int y = 0;
while (x > 0){
y=x+y;
cin>>x;
}
return y ;
}

3. I'm guessin you want to prompt for the second varible "b" to get the sum of both. In this case b has no value when its given to the other function, so only garbage (leftover in memory location) will be given.

EDIT: Doh, beat me, I knew I shouldn't have gone upstairs for that coke =P

4. You need to use a return type before the name of the function in the function definition.

Most people don't view 0 as a negative number though, so I might change the while conditional to:

while(x >= 0);

Also if additional user input beyond the initial input is to be given in FindSum() then we should be kind enough to ask for it:

Here's what I would do assuming b is initialized to zero in main():

int FindSum(int x, int y)
{
while (x >= 0){
y += x;
cout << "enter another non-negative number to continue or negative number to stop."
cin>>x;
}
return y ;
}

Popular pages Recent additions