Introduction
- The
for
statement: executes its body while a specified Boolean expression (the ‘condition’) evaluates to true. - The
foreach
statement: enumerates the elements of a collection and executes its body for each element of the collection. - The
do-while
statement: conditionally executes its body one or more times. - The
while
statement: conditionally executes its body zero or more times.
FizzBuzz with the for
statement
FizzBuzz is a popular coding challenge and interview question. It exercises your understanding of the for statement, the if
statement, the %
remainder operator, and your command of basic logic.
Challenge rules
- Output values from 1 to 100, one number per line, inside the code block of an iteration statement.
- When the current value is divisible by 3, print the term Fizz next to the number.
- When the current value is divisible by 5, print the term Buzz next to the number.
- When the current value is divisible by both 3 and 5, print the term FizzBuzz next to the number.
Challenge solution
Here is a simple solution to the FizzBuzz challenge in C#:
1
2
3
4
5
6
7
8
9
10
11
| for (int i = 1; i < 101; i++)
{
if ((i % 3 == 0) && (i % 5 == 0))
Console.WriteLine($"{i} - FizzBuzz");
else if (i % 3 == 0)
Console.WriteLine($"{i} - Fizz");
else if (i % 5 == 0)
Console.WriteLine($"{i} - Buzz");
else
Console.WriteLine($"{i}");
}
|
The do-while statement
- The do-while statement executes a statement or a block of statements while a specified Boolean expression evaluates to true.
- Because that expression is evaluated after each execution of the loop, a do-while loop executes at least once and might continue to iterate based on a Boolean expression.
1
2
3
4
| do
{
// This code executes at least one time
} while (true);
|
- An example of a do-while loop that prints the numbers from 1 to 10:
1
2
3
4
5
6
| int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i <= 10);
|
- An example of a do-while loop that will keep generating random numbers between 1 and 10 until we generate the number 7. It could take just one iteration to get a 7, or it could take dozens of iterations.
1
2
3
4
5
6
7
8
| Random random = new Random();
int currentNumber = 0;
do
{
currentNumber = random.Next(1, 11);
Console.WriteLine(currentNumber);
} while (currentNumber != 7);
|
The continue
statement
- The
continue
statement is used to skip the current iteration of a loop and continue with the next iteration. - In the following example, we generate random numbers between 1 and 10, and we only print the numbers that are less than 8:
1
2
3
4
5
6
7
8
9
10
11
| Random random = new Random();
int current = random.Next(1, 11);
do
{
current = random.Next(1, 11);
if (current >= 8) continue;
Console.WriteLine(current);
} while (current != 7);
|
The while
statement
- The while statement evaluates a Boolean expression first, and continues to iterate through the code block as long as the Boolean expression evaluates to true.
1
2
3
4
5
6
7
8
9
| Random random = new Random();
int current = random.Next(1, 11);
while (current >= 3)
{
Console.WriteLine(current);
current = random.Next(1, 11);
}
Console.WriteLine($"Last number: {current}");
|
- The code block will execute as long as the current number is greater than or equal to 3.
The Battle Game
- Here are the rules for the battle game that you need to implement in your code project:
- You must use either the do-while statement or the while statement as an outer game loop.
- The hero and the monster start with 10 health points.
- All attacks are a value between 1 and 10.
- The hero attacks first.
- Print the amount of health the monster lost and their remaining health.
- If the monster’s health is greater than 0, it can attack the hero.
- Print the amount of health the hero lost and their remaining health.
- Continue this sequence of attacking until either the monster’s health or hero’s health is zero or less.
- Print the winner.
- Expected output:
1
2
3
4
5
6
| Monster was damaged and lost 1 health and now has 9 health.
Hero was damaged and lost 1 health and now has 9 health.
Monster was damaged and lost 7 health and now has 2 health.
Hero was damaged and lost 6 health and now has 3 health.
Monster was damaged and lost 9 health and now has -7 health.
Hero wins!
|
Challenge solution 1
- Here is one possible solution to the battle game challenge using the
do-while
statement:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| int hero = 10;
int monster = 10;
Random dice = new Random();
do
{
int roll = dice.Next(1, 11);
monster -= roll;
Console.WriteLine($"Monster was damaged and lost {roll} health and now has {monster} health.");
if (monster <= 0) continue;
roll = dice.Next(1, 11);
hero -= roll;
Console.WriteLine($"Hero was damaged and lost {roll} health and now has {hero} health.");
} while (hero > 0 && monster > 0);
Console.WriteLine(hero > monster ? "Hero wins!" : "Monster wins!");
|
- Here is another possible solution to the battle game challenge using the
while
statement:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| int hero = 10;
int monster = 10;
Random dice = new Random();
while (hero > 0 && monster > 0)
{
int roll = dice.Next(1, 11);
monster -= roll;
Console.WriteLine($"Monster was damaged and lost {roll} health and now has {monster} health.");
if (monster <= 0) break;
roll = dice.Next(1, 11);
hero -= roll;
Console.WriteLine($"Hero was damaged and lost {roll} health and now has {hero} health.");
}
Console.WriteLine(hero > monster ? "Hero wins!" : "Monster wins!");
|
Console.ReadLine() and Looping
- The
Console.ReadLine()
method reads the next line of characters from the standard input stream. - The following code sample uses a
nullable type string (string?)
to capture user input. The iteration continues while the user-supplied value is null:
1
2
3
4
5
6
7
| string? readResult;
Console.WriteLine("Enter a string:");
do
{
readResult = Console.ReadLine();
} while (readResult == null);
Console.WriteLine($"You entered: {readResult}");
|
- The following example prompts the user to enter a string that includes at least three characters:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| string? readResult;
bool validInput = false;
Console.WriteLine("Enter a string with at least three characters:");
do
{
readResult = Console.ReadLine();
if (readResult != null)
{
if (readResult.Length >= 3)
{
validEntry = true;
}
else
{
Console.WriteLine("Your input is invalid, please try again.");
}
}
} while (validEntry == false);
|
The int.TryParse()
method
- The
int.TryParse()
method converts the string representation of a number to its 32-bit signed integer equivalent. - A return boolean value indicates whether the conversion succeeded.
1
2
3
4
5
6
| // capture user input in a string variable named readResult
int numericValue = 0;
bool validNumber = false;
validNumber = int.TryParse(readResult, out numericValue);
|
Code Projects and Challenges
Rules
1
2
3
4
5
6
7
| Enter an integer value between 5 and 10
two
Sorry, you entered an invalid number, please try again
2
You entered 2. Please enter a number between 5 and 10.
7
Your input value (7) has been accepted.
|
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| string? readResult;
string valueEntered = "";
int numValue = 0;
bool validNumber = false;
Console.WriteLine("Enter an integer value between 5 and 10");
do
{
readResult = Console.ReadLine();
if (readResult != null)
{
valueEntered = readResult;
}
validNumber = int.TryParse(valueEntered, out numValue);
if (validNumber == true)
{
if (numValue <= 5 || numValue >= 10)
{
validNumber = false;
Console.WriteLine($"You entered {numValue}. Please enter a number between 5 and 10.");
}
}
else
{
Console.WriteLine("Sorry, you entered an invalid number, please try again");
}
} while (validNumber == false);
Console.WriteLine($"Your input value ({numValue}) has been accepted.");
readResult = Console.ReadLine();
|
Rules
1
2
3
4
5
| Enter your role name (Administrator, Manager, or User)
Admin
The role name that you entered, "Admin" is not valid. Enter your role name (Administrator, Manager, or User)
Administrator
Your input value (Administrator) has been accepted.
|
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| string? readResult;
string roleName = "";
bool validEntry = false;
do
{
Console.WriteLine("Enter your role name (Administrator, Manager, or User)");
readResult = Console.ReadLine();
if (readResult != null)
{
roleName = readResult.Trim();
}
if (roleName.ToLower() == "administrator" || roleName.ToLower() == "manager" || roleName.ToLower() == "user")
{
validEntry = true;
}
else
{
Console.Write($"The role name that you entered, \"{roleName}\" is not valid. ");
}
} while (validEntry == false);
Console.WriteLine($"Your input value ({roleName}) has been accepted.");
readResult = Console.ReadLine();
|
Process the contents of a string array
Rules
- Your solution must use the following string array to represent the input to your coding logic:
1
| string[] myStrings = new string[2] { "I like pizza. I like roast chicken. I like salad", "I like all three of the menu choices" };
|
- Your solution must declare an integer variable named periodLocation that can be used to hold the location of the period character within a string.
- Your solution must include an outer foreach or for loop that can be used to process each string element in the array. The string variable that you’ll process inside the loops should be named myString.
- In the outer loop, your solution must use the IndexOf() method of the String class to get the location of the first period character in the myString variable. The method call should be similar to: myString.IndexOf(“.”). If there’s no period character in the string, a value of -1 will be returned.
- Your solution must include an inner do-while or while loop that can be used to process the myString variable.
- In the inner loop, your solution must extract and display (write to the console) each sentence that is contained in each of the strings that are processed.
- In the inner loop, your solution must not display the period character.
- In the inner loop, your solution must use the Remove(), Substring(), and TrimStart() methods to process the string information.
1
2
3
4
| I like pizza
I like roast chicken
I like salad
I like all three of the menu choices
|
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| string[] myStrings = new string[2] { "I like pizza. I like roast chicken. I like salad", "I like all three of the menu choices" };
int stringsCount = myStrings.Length;
string myString = "";
int periodLocation = 0;
for (int i = 0; i < stringsCount; i++)
{
myString = myStrings[i];
periodLocation = myString.IndexOf(".");
string mySentence;
// extract sentences from each string and display them one at a time
while (periodLocation != -1)
{
// first sentence is the string value to the left of the period location
mySentence = myString.Remove(periodLocation);
// the remainder of myString is the string value to the right of the location
myString = myString.Substring(periodLocation + 1);
// remove any leading white-space from myString
myString = myString.TrimStart();
// update the comma location and increment the counter
periodLocation = myString.IndexOf(".");
Console.WriteLine(mySentence);
}
mySentence = myString.Trim();
Console.WriteLine(mySentence);
}
|