STOP PRESS! The full book is now available DIRECTLY from Amazon with lower shipping costs!
This quiz program uses a loop to ask ten randomly generated questions.
The answers that the user types are checked to determine whether they are valid integers.
The program also guards against a division-by-zero error through the use of a while loop that repeatedly chooses a new denominator until obtaining one that is not zero.
Select and copy the C++ source-code at the bottom of this post.
Paste into a text editor, such as Nano or Geany.
Then save the new file, ending in .cpp
I used quiz.cpp
To compile from the command-line:
g++ -o quiz.cpp quiz
To run from the command-line:
./quiz
Code is below...
#include <iostream> // Screen output
#include <cstdlib> // random() and srandom() functions
#include <unistd.h> // time() function
#include <climits> // INT_MAX constant when validating input
using namespace std;
int main()
{
// Seed the random numbers
srandom( time( 0 ) );
// Variables needed during quiz
int num1, num2, kind, answer, guess;
char symbol;
bool haveValidGuess;
// Keep track of how many questions asked and how many correct
int numCorrect = 0;
int questionNum = 1;
while ( questionNum <= 10 )
{
// Choose 2 random numbers between 0-12
num1 = random() % 13;
num2 = random() % 13;
// Choose what to do with them
kind = random() % 4; // 4 kinds of question
if ( kind == 0 )
{
answer = num1 + num2;
symbol = '+';
}
if ( kind == 1 )
{
answer = num1 - num2;
symbol = '-';
}
if ( kind == 2 )
{
answer = num1 * num2;
symbol = '*';
}
if ( kind == 3 )
{
// Double check not trying to divide by zero
while ( num2 == 0 )
num2 = random() % 13;
num1 *= num2; // Ensure is whole number division
answer = num1 / num2;
symbol = '/';
}
// Ask the question
cout << "Question " << questionNum << endl;
// User supplies their answer
haveValidGuess = false;
while ( not haveValidGuess )
{
cout << num1 << symbol << num2 << " is?" << endl;
cin >> guess;
// Check was a valid integer
if ( cin.good() )
haveValidGuess = true;
else
{
// Clear out channel-in keyboard buffer
cin.clear();
cin.ignore( INT_MAX, '\n' );
}
} // end of while loop that validates data entry
// Check whether answer is correct
if ( guess == answer )
{
cout << "Correct!" << endl;
numCorrect++;
}
else
{
cout << "Sorry - that's not the answer!" << endl;
cout << num1 << symbol << num2 << " is " << answer << endl;
} // end of if-else decision that checks answer
// Leave a blank line before next question
cout << endl;
questionNum++;
} // end of while loop that repeatedly asks questions
// Display final score
cout << endl << "End of quiz" << endl << endl;
cout << "You scored " << numCorrect;
cout << " out of " << questionNum - 1 << endl;
return 0;
}
Find out more - buy the book on Amazon...