Control structures
Your solution should also make use of control structuresthe method control the direction of your program's execution. Without control a program will run in the order it appears. The ability to change the order of execution depending on parameters makes a program more powerful. . Provide evidence that you have used the following control structures:
- conditional execution:
if
- conditional execution with alternative:
if-else
- looping:
for-while, repeat
Python implementation
28 def numberGenerator():# function to generate random number
29 num = random.randint(1,12)
30 return num
31
32 score = 0
33 def addQuestion():
34 '''Function to create and correct addition questions'''
35 num1 = numberGenerator()#Generate 2 random numbers for the questions
36 num2 = numberGenerator()
37 userAns = int(input('What is {} + {} ?: '.format(num1, num2)))# Ask question & capture answer
38 if userAns == num1 + num2: # if correct answer, increment score & feedback to user
39 print('Correct')
40 global score #references the global variable score & increments
41 score += 1
42 else:
43 print('Incorrect')
Line 38 compares the user's answers to the correct answer and then will execute one of two clauses depending on the user's input:
What is 8 + 4?: 11
Incorrect
Press any key to continue . . .
OR
What is 8 + 4?: 12
Correct
Press any key to continue . . .
C# implementation
static void addQuestion()
{
Random ran1 = new Random();
int num1 = ran1.Next(0,10);
Random randT = new Random(DateTime.Now.Millisecond);
int num2 = randT.Next(0,10);
Console.Write("What is " + num1 + "+" + num2 + " ?: ");
int answer = Convert.ToInt32(Console.ReadLine());
if(answer == num1+num2)
{
Console.WriteLine("Correct!");
Console.WriteLine("Score +1");
score = score + 1;
}
else
{
Console.WriteLine("Incorrect.");
}
}
This code generates two distinct random numbers by employing two strategies to obtain random values, thus making it highly unlikely they will be identical.
Here is an example of a negative outcome – an incorrect answer being supplied by the user:
Enter a name: Fred
Fred >> Accepted
DIFFICULTY
Please select the difficulty level from the menu below:
1 - Easy
2 - Medium
3 - Hard
2
Level chosen = 2
What is 0 + 5?: 6
Incorrect.
Press any key to continue . . .
Here is an example of a positive outcome – a correctly answered question:
Enter a name: Francis
Francis >> Accepted
DIFFICULTY
Please select the difficulty level from the menu below:
1 - Easy
2 - Medium
3 - Hard
2
Level chosen = 2
What is 6 + 9?: 15
Correct!
Score +1
Press any key to continue . . .