Loop structures are helpful when repeating statements; for example, if we wanted to print out a message to the console, or if we want to call a function. There are several types of loops that can be used, and each has their own strength. We'll look at do-while, for, and while C# loops. The other common loop, foreach, is used to iterate through a collection (like an array). After we look at some examples of loops we'll build an application to write out song lyrics.
To show the different types of loops, we'll make a function that we can call multiple times. Since we are going to eventually be printing out lyrics to a song about bears, we'll make the function show an ASCII design of a bear. We'll also review some C# language basics, too.
Bear Function
If we want alphanumeric characters written to the console in the shape of a bear, and we plan on repeating that bear several times, we can package our statements in a function. This allows us to easily use the design in multiple places. We define it once, and then can call it wherever we want a bear to appear. We can also use a loop to repeatedly call our function if we want more than one bear to appear.
Keywords
To define the bear function, we will use the keywords static and void, and the identifier MakeBear.
static
We are not going to create an instance of the parent class (Program) before calling our MakeBear function. To call a method of the class (instead of calling a method of a specific object) we need to use the modifier keyword static.
void
Functions can return a value. If no value will be returned use the keyword void.
identifier
An identifier is a name programmers choose for elements they create (like a class, method, or variable).
Function Body
Inside the body* of our MakeBear function we'll define a string that holds the bear design. WriteLine will be used to write out the bear.
static void MakeBear() { //body of the function }
*The body of the function is inside a code block that starts with an opening curly brace and ends with a closing one.)
Verbatim Strings
There is an @ symbol in front of the start of our string because the string spans multiple lines. You can also use the @ symbol if you have multiple lines of dialogue or other types of multi-line text content that you want stored in a string. Make sure that you have double-quote marks around the characters in your string.
static void MakeBear() { string bear = @" {''-''} (o o) ,--`Y'--. ``: ;'' / _ \ ()' `() "; Console.WriteLine(bearImage); }
If we want to print out the bear we call the MakeBear function (calling a function is also known as invoking it).
MakeBear();
Starting Code
We'll first look at an example of calling the MakeBear function as many times as we want our bear to be printed out (this isn't as efficient as using a loop)
using System; namespace Bears { class Program { static void Main() { MakeBear(); MakeBear(); MakeBear(); Console.ReadLine(); } static void MakeBear() { string bear = @" {''-''} (o o) ,--`Y'--. ``: ;'' / _ \ ()' `() "; Console.WriteLine(bear); } } }
The MakeBear function was invoked three times, and each time a bear was written to the console window.
While Loops
The structure of a while loop:
while(expression) { //statements }
A while loop will run as long as the expression within the parentheses is true (while we have not gotten the total number of bears, continue looping).
Inside our Main function we will declare and initialize two variables. The first, bearsNeeded, will hold the number of bears we want to make. The second, bearTotal, will track the total number of bears that have been made.
We'll give our counter bearTotal a value of zero initially. Giving the variable that is tracking how many times a loop has run an initial value is called counter initialization.
Let's make six bears.
int bearsNeeded=6; int bearTotal=0;
Next we want to set up our expression. We'll tell our loop that while bearTotal is less than bearsNeeded, keep looping. Inside the loop's code block we'll call the MakeBear function.
while(bearTotal<bearsNeeded) { //statements }
We'll also want to increment our bearTotal after each call to the MakeBear function.
We could use this:
bearTotal = bearTotal + 1;
But there is an alternative we'll use instead. The increment operator (++) increments by 1, and is a shorter way of writing out bearTotal = bearTotal + 1.
bearTotal++;
Our while loop now looks like this:
while(bearTotal<bearsNeeded) { MakeBear(); bearTotal++; }
Now that we have our loop in our code, we can run it and see six bears written to the console window.
While Loop Code
using System; namespace Bears { class Program { static void Main() { int bearsNeeded=6; int bearTotal=0; while(bearTotal<bearsNeeded) { MakeBear(); bearTotal++; } Console.ReadLine(); } static void MakeBear() { string bear = @" {''-''} (o o) ,--`Y'--. ``: ;'' / _ \ ()' `() "; Console.WriteLine(bear); } } }
Do-While Loops
The structure of this type of loop is first the keyword do, then a code block, and finally the expression.
do { //statements } while(expression)
A do-while loop will always run at least once. In this case we will always get at least one bear even if bearTotal is greater than bearsNeeded before we begin. Below you can see our code with a do-while loop added. By the time the application gets to this new loop we've already made six bears (from the first while loop). Because a do-while loop will always run at least once, we'll get one more bear printed out even though bearTotal will be six and the expression in the do-while loop will be false.
In this next version the type of loop will be written to the screen before the loop starts to make it easier to see when each starts, as well as the current total bear amount.
Do-While Loop Code
using System; namespace Bears { class Program { static void Main() { int bearsNeeded=6; int bearTotal=0; Console.WriteLine("A while loop. Total bears: " + bearTotal); while(bearTotal<bearsNeeded) { MakeBear(); bearTotal++; } Console.WriteLine("A do while loop. Total bears: " + bearTotal); do { MakeBear(); bearTotal++; }while(bearTotal<bearsNeeded); Console.ReadLine(); } static void MakeBear() { string bear = @" {''-''} (o o) ,--`Y'--. ``: ;'' / _ \ ()' `() "; Console.WriteLine(bear); } } }
Even though the total number of bears was six before the do while loop was reached, the do-while loop still printed out a bear because the expression it was testing for (bearTotal<bearsNeeded) is after the code block.
For Loops
A for loop collapses the counter initialization, the expression, and the increment into a header.
int total = 2; for (int counter = 0; counter < total; counter++) { //statements }
In the above example instead of having two variables declared outside of the loop structure like our earlier loops we have only one: total. The other variable, the counter, is initialized in the header. The increment is no longer in the code block - that too has been moved to the header. Let's add a for loop to our example code and write out two more bears.
For Loop Code
using System; namespace Bears { class Program { static void Main() { int bearsNeeded=6; int bearTotal=0; Console.WriteLine("A while loop. Total bears: " + bearTotal); while(bearTotal<bearsNeeded) { MakeBear(); bearTotal++; } Console.WriteLine("A do while loop. Total bears: " + bearTotal); do { MakeBear(); bearTotal++; }while(bearTotal<bearsNeeded); Console.WriteLine("A for loop."); int total = 2; for (int counter = 0; counter < total; counter++) { MakeBear(); } Console.ReadLine(); } static void MakeBear() { string bear = @" {''-''} (o o) ,--`Y'--. ``: ;'' / _ \ ()' `() "; Console.WriteLine(bear); } } }
C# Loops: Ten Bears Song
Now that we have examples of loops we can use this knowledge to print out the lyrics to a song about our bears.
- First line: Ten bears in the bed and the little one said "I'm crowded... roll over" so they all rolled over and one fell out...
- Second line: Nine bears in the bed and the little one said "I'm crowded... roll over" so they all rolled over and one fell out...
- Continues until the last line....
- One bear in the bed and the little one said "I'm lonely"
Since we are starting with ten bears and counting down we can use the decrement operator instead of increment (-- instead of ++). We'll also want to watch for the change between the plural in the majority of the lines and the singular in the last line. To make that change easier we'll use numbers instead of words for the bear amount (i.e., 10 bears instead of ten bears).
We can also add a title to the application's title bar to make it look nicer.
Ten Bears Code
using System; //programmingisfun.com namespace TenBears { class Program { static void Main() { Console.Title = "Ten Bears"; for (int currentBears = 10; currentBears > 1; currentBears--) { Console.WriteLine(currentBears + " bears in the bed and the little one said \"I'm crowded... roll over...\""); Console.WriteLine("So they all rolled over and one fell out...\n"); } Console.WriteLine("One bear in the bed and the little one said \"I'm lonely\""); MakeBear(); Console.ReadLine(); } static void MakeBear() { string bear = @" {''-''} (o o) ,--`Y'--. ``: ;'' / _ \ ()' `() "; Console.WriteLine(bear); } } }
Read Repetitive Lyrics Using Arrays & Nested Loop to see how arrays and a nested loop can be used to write out the lyrics to the song "There Was an Old Lady Who Swallowed a Fly".