C++ program that ask the user five random addition problems
Posted by Samath
Last Updated: November 15, 2014

Create a C++ program that displays five random addition problems, one at a time, on the computer screen. Each problem should be displayed as a question, like this: What is the sum of x + y? The x and y in the question represent numbers from 1 to 10, inclusive. After displaying the question, the program should allow the user to enter the answer. It then should compare the user’s answer with the correct answer. If the user’s answer matches the correct answer, the program should display the “Correct!” message. Otherwise, it should display the “Sorry, the answer is” message followed by the correct answer and a period. Use separate functions to generate the question and check the user’s answer.

Solution:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void checkAnswer(int answer, int userAnswer);
int generateQuestion();

	int x;
	int y;
	
int main(int argc, char *argv[])
{
	srand (time(NULL));
for(int i=0;i<5;i++)
{
	int answer;
	int userAnswer;
	
	answer = generateQuestion();
	cin>>userAnswer;
	checkAnswer(answer,userAnswer);
}		
	return 0;
}

int generateQuestion()
{
    int answer;
	
	x = 1 + rand()%10;
	y = 1 + rand()%10;
	answer=x+y;
	cout<<"What is the sum of "<<x <<"+"<< y<<"?";
	
	return answer;
}

void checkAnswer(int answer, int userAnswer)
{
	if(answer == userAnswer)
	{
		cout<<"Correct!\n\n";
	}
	else if(answer != userAnswer)
	{
		cout<<"Sorry, the answer is "<<answer<<".\n\n";
	}
}