Contents

Kata 7 solution

Q1

This one is simple. First, make sure you increase the array size to 3 when it’s declared:

string[] questions = new string[3];

Add new questions and answers to the arrays:

questions[2] = "What's up, dog?";
answers[2] = "Not much my G";

Remember arrays are zero indexed - they start at 0 instead of 1 - so the 3rd index in the array is actually index number 2!

In the for loop, make sure the loop condition checks if i is less than 3 instead of 2.

Q2

The first step to converting the for loop to a while loop is to set up the loop conditions. We know that the loop needs to iterate through all the questions in the array. We also need a variable to keep track of the current index in the array. It might look like this:

int currentIndex = 0;

while (currentIndex < 3) {

}

Next, add the code to ask the questions using currentIndex:

int currentIndex = 0;

while (currentIndex < 3) {
    AskQuestion(questions[currentIndex], answers[currentIndex]);
    currentIndex++;
}

We also have to make sure currentIndex is incremented each time the loop completes.

Next let’s re-introduce the logic to check if the user has won or lost:

bool hasUserWon = true;
int currentIndex = 0;

while (currentIndex < 3) {
    bool questionResult = AskQuestion(questions[currentIndex], answers[currentIndex]);

    if (questionResult == false) {
        hasUserWon = false;
    }

    currentIndex++;
}

The do...while loop is largely the same:

bool hasUserWon = true;
int currentIndex = 0;

do {
    bool questionResult = AskQuestion(questions[currentIndex], answers[currentIndex]);

    if (questionResult == false) {
        hasUserWon = false;
    }

    currentIndex++;
} while (currentIndex < 3);
Copyright Mikiel Agutu 2019