Functions and loops, not getting desired output

Oct 29, 2014 at 11:53pm
This program is supposed to take input from getbottles function and return it based on what the user enters. When I compile, nothing happens.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  #include <iostream>

using namespace std;

int getBottles(int todayBottles, int totalBottles, int counter);

int main()
{
	//getBottles function
	int totalBottles = 0;
	int todayBottles = 0;
	int counter =1 ;
	cout << "Welcome to the bottle calculation program!" << endl;
	getBottles(todayBottles, totalBottles, counter);
	return 0;
}

int getBottles(int todayBottles, int totalBottles, int counter)
{
	for(counter = 1; counter <7; counter++)
	{
		cout << "Enter number of bottles returned: ";
		cin >> todayBottles;

		while (todayBottles != -1)
		{
			if(todayBottles <= 0)
			{
				cout << "Invalid Bottle Amount." << endl;
			}

			else 
			{
				totalBottles = totalBottles + todayBottles;
				return totalBottles;
			}			
		}
	}
	return false;
}
Oct 30, 2014 at 12:08am
what is the purpose of the while loop there? You never seem to alter the todayBottles value so that it is equal to negative 1, and that return statement just ends getBottles. Also, there is no output saying anything after getBottles, which is the reason it looks like your program isn't working, when in fact, it is. Are you trying to get 6 different totalBottles values?
Oct 30, 2014 at 12:17am
the while loop is there so that if the user enters a negative value, it ends the program. I wasn't sure where to put the output either. And to answer the last question, yes I'm trying to get 6 values for totalBottles.

some of it might seem redundant though. do I need the if/else statements if I already have that while?
Oct 30, 2014 at 12:49am
I think that you should just get rid of the while loop. The if else statement already checks if the value entered is negative, and if a person enters -2 or lower, the error message prints, but the program continues. Besides, if the person enters a positive value like you want, the return statement causes the function to end, so even in the best case, you never get more than 1 value. If you want the seven values, just put the function call to getBottles in a for loop in main(), get rid of the for loop in getBottles because it isn't doing anything, and print out the values after each call. ex.
1
2
3
4
for (counter = 0; counter < 6; counter++) {
cout << getBottles(todayBottles, totalBottles) << "\n";
}
Oct 30, 2014 at 12:51am
also, get rid of passing the counter, as it is now in main, and also, why not move all of the int's into getBottles? There really isn't much of a reason to keep them in main anymore.
Oct 30, 2014 at 4:58am
ok, made changes you suggested, programming works as intended. thanks!
Topic archived. No new replies allowed.