Skip to content

Instantly share code, notes, and snippets.

@Dyrits
Forked from codecademydev/Program.cs
Last active May 10, 2023 08:08
Show Gist options
  • Save Dyrits/c0d3f85ba8ebe8a9b757efba0810ee77 to your computer and use it in GitHub Desktop.
Save Dyrits/c0d3f85ba8ebe8a9b757efba0810ee77 to your computer and use it in GitHub Desktop.
True or False?

True or False?

You’re taking an interactive quiz written in C#. Everything is going fine until you respond to this question:

Example #1

This application wasn’t checking your input. When you used an unexpected format, it couldn’t ask the question again and marked your answer as wrong. (By botanical definition, eggplants really are berries!).

In this project, you’ll build a C# program that presents a quiz the right way: using arrays and loops, it will check the format of user input and repeat the question if the format is incorrect. After the quiz is complete, it will check the user’s responses against the correct answers and present a score.

Exemple #2

Let’s get started!

using System;
namespace TrueOrFalse
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to 'True or False?'\nPress Enter to begin:");
string entry = Console.ReadLine();
Tools.SetUpInputStream(entry);
string[] questions = { "Eggplants are a type of berry.", "Peanuts are not nuts!", "Copyrights depreciate over time.", "Emus can’t fly.", "Electrons move faster than the speed of light.", "Light travels in a straight line.", "People may sneeze or cough while sleeping deeply.", "There is no snow on Minecraft." };
bool[] answers = { true, true, true, true, false, true, false, false };
bool[] responses = new bool[questions.Length];
if (questions.Length != answers.Length)
{
Console.WriteLine("The number of questions doesn't mathc the number of answers.");
}
int askingIndex = 0;
foreach (string question in questions)
{
Console.WriteLine(question);
Console.WriteLine("True or false?");
bool isBool = false;
while(!isBool)
{
string input = Console.ReadLine();
isBool = Boolean.TryParse(input, out bool inputBool);
if (!isBool) { Console.WriteLine("Please respond with 'true' or 'false'."); }
else { responses[askingIndex ++] = inputBool; }
}
}
int scoringIndex = 0;
int score = 0;
foreach (bool answer in answers)
{
bool response = responses[scoringIndex ++];
Console.WriteLine($"{scoringIndex}. Input: {response} | Answer: {answer}");
if (response == answer) { score ++; }
}
Console.WriteLine($"You got {score} out of {scoringIndex} correct!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment