event controlled loops & functions

I made a program that generates addition problems, and the user enters the answer in and it notifies the user whether it is correct or not. Initially my program worked, but when I tried to make the program have an even controlled loop, as in only outputting 5 problems with every run of the program. Once I tried doing that, I started receiving compiler errors:

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
#include <iostream>
using namespace std;

void additionProblem(int topNumber, int bottomNumber)
{


   total = 0;
   additionProblem = 1;	
while (additionProblem >= 5){

int userAnswer;
cout << "\n\n\n " << topNumber << " + " << bottomNumber << " = ";
cin >> userAnswer;
cin.ignore(1000, 10);
int theAnswer = topNumber + bottomNumber;
if (theAnswer == userAnswer)
cout << " Correct!" << endl;
else
cout << " Very good, but a better answer is " << theAnswer << endl;
  }
} // additionProblem


int main()
{
additionProblem(rand() % 10, rand() % 10);
additionProblem(rand() % 10, rand() % 10);
additionProblem(rand() % 10, rand() % 10);
additionProblem(rand() % 10, rand() % 10);
additionProblem(rand() % 10, rand() % 10);

return 0;
} // main 
closed account (o3hC5Di1)
Hi there,

Although it's best to post your compiler errors along with the code, this one was easy to spot:

1
2
3
4
5
6
//line 3
void additionProblem(int topNumber, int bottomNumber)
{
   total = 0;
   additionProblem = 1;	
while (additionProblem >= 5){


You haven't declared the total, nor additionProblem variable. Also, the additionProblem variable has the exact same name as void additionProblem(int topNumber, int bottomNumber) which is not allowed.
On a sidenote, your while expression states that it will run as long as your counter is larger than or eaual to five, which will never happen if you initialise it to one like you did.

Here's the fix:

1
2
3
4
5
6
7
8
//line 3
void additionProblem(int topNumber, int bottomNumber)
{
   total = 0; //remove this, you're not using it
   additionProblem = 1;
   int counter = 1; //declare a counter as int, starting at 1
while (counter <= 5){  // while counter is smaller than or equal to 5
counter++; //don't forget to actually increase the counter or your loop will run forever. 


For cases like this it's generally cleaner to use a for-loop rather than a while loop.
For more information on that see http://cplusplus.com/doc/tutorial/control/#for

Hope that helps.

All the best,
NwN
Last edited on
Topic archived. No new replies allowed.