Today you will write a computer program that can play an old children’s game cal
ID: 667517 • Letter: T
Question
Today you will write a computer program that can play an old children’s game called “BAM”. This is an “elimination” game with rather simple rules:
The first player yells the number 1 (“one!”)
Each player in succession yells the number called by the previous player, plus one. Thus, at the beginning of the game, the second player would yell “two!”.
However, when the number in turn is either divisible by 3 (like the number 12, for example) or ends in 3 (like the number 23), the player is supposed to yell “BAM!”. (Hence, this would be a correct sequence of numbers: 1, 2, BAM, 4, 5, BAM, 7, 8, BAM, 10, 11, BAM, BAM, 14, BAM, 16, etc.)
If the player gets distracted and yells the wrong number instead of BAM, he or she would be eliminated from the game.
The game continues, played faster and faster, until just one player remains – the winner of the game.
Your assignment is to write a computer code that can generate a correct sequence, starting from the number 1; the end of the sequence will be chosen by the user, input through the keyboard.
To determine if the number is divisible by 3, you need an if statement to test the condition, specifically if (number % 3 == 0). To test if the number ends in 3, you would use if (number % 10 == 3). Satisfying either of these tests should generate an output of the word BAM!, using a cout statement. Remember to proceed to the next number in the counter sequence, after producing the BAM output. (Hint: combine the two “ifs” in one statement.)
In the actual run, you will need to prompt the user to choose the final number in the sequence, starting from the number 1, and then proceed to output the list to the screen.
Explanation / Answer
#include <iostream>
using namespace std;
// C++ Program to generate sequence of BAM Game
int main() {
//declare variable
int num;
// prompt user to enter an integer value
cout<<"Please enter an integer value: ";
cin>>num;
cout<<endl; // go to next line
// run a for loop from 1 to num
for(int i = 1; i <= num; i++)
{
if(i==1)
cout<<i;
else if((i % 3 == 0) || (i % 10 == 3)) // check whether i is divided by 3 or its ending with 3. If yes, print "BAM"
cout<<", BAM";
else
cout<<", "<<i;
}
return 0;
}