C# Beginners – Loops

For Loop FlowChart

C# Beginners – Loops; covers the basics of writing loops in C#. Looping is a fundamental part of almost every program. This tutorial assumes you are familiar with Lists, Arrays and selection. If this is not the case, please see earlier tutorials in this series. This tutorial covers all iterative loop types (for, foreach, while and do while) but does not cover recursion. Recursion will come after methods in the tutorials. A video version is available at the bottom of the post or by clicking here.

For Loop FlowChart - C# Beginners - Loops
For Loop FlowChart

Looping typically works in one of four ways:

  1. The operation executes a specific number of times.

    You can achieve this with a for or while loop, but it is usually a forloop.
  2. An operation happens to all elements in a list or an array.

    This can be a for or while loop, but, usually a foreach loop.
  3. The code block executes over and over until it meets the condition set.

    A while loop performs this operation.
  4. A code block executes once and then in a cycle until it meets the condition.

    This is a derivative of the while loop called a do while loop.

For Loop – C# Beginners – Loops

We use a for-loop when an operation needs to execute a specific number of times. Additionally, we use them to process lists and arrays requiring a specific start and end index.

Flowchart

For Loop FlowChart
For Loop FlowChart

Code

int number;

for (number = 0; number < 10; number++)
{
    Console.WriteLine(number.ToString());
}
  1. A variable called ‘number’ is declared, and its type is set to an integer.
  2. The value of ‘number’ is set to 0.
  3. It checks to see if the value of ‘number’ is less than 10.
  4. It increases the value of ‘number’ by 1.
  5. Runs the code block contents.
  6. Check again to see if the value of ‘number’ is less than 10.
  7. Adds 1 to the value of ‘number’.
  8. Run the code block contents.
  9. Repeat 5-7 until the condition does not occur.
  10. Exit the loop.

Output

0
1
2
3
4
5
6
7
8
9

Foreach Loop – C# Beginners – Loops

Foreach loops are used when one or more operations must happen to each list element or array element. These loops will always start with the first element and end with the last.

Flowchart

Foreach Loop FlowChart - C# Beginners - Loops
Foreach Loop FlowChart

Code

List<string> words;
 words = new List<string>()
 {
     "Word1", "Word2", "Word3", "Word4", "Word5",
     "Word6", "Word7", "Word8", "Word9", "Word10"
 };
 
 foreach (string word in words)
 {
     Console.WriteLine(word);
 }

Description

  1. The variable called words is declared, and its element type is set to string.
  2. Ten elements are assigned to the variable, each containing a string.
  3. Check to see if all elements in the list have been processed.
  4. If they have not, then run the code block contents for this element.
    In this code, it runs Console.Writeline to output the string to the console.
  5. Reat 3-4 until all elements have been processed

Output

Word1
Word2
Word3
Word4
Word5
Word6
Word7
Word8
Word9
Word10

While Loop – C# Beginners – Loops

A while loop will continue to run until a specific condition is met. It is possible to use them similarly to a For loop. However, they commonly check for a condition that will change inside the while loops code block. The example below is for testing user input.

Flowchart

While Loop FlowChart
While Loop FlowChart

Code – C# Beginners – Loops

string yesNo; 
yesNo = string.Empty;

while (yesNo != "y")
{
    Console.WriteLine("Please enter a lower " +
                      "case \"y\" and press enter");
    yesNo = Console.ReadLine();
}

Note 1: The code enters the while loop if the variable is NOT equal to ‘y’

Note 2: The output will depend on the input.

Description

This code does the following:

  1. Declares a string variable called ‘yesNo’.
  2. Assign an empty string to the variable.
  3. Check to see if the variable is not equivalent to a lowercase ‘y’.
  4. If it is not equivalent to a lowercase, ‘y’ enter the code block.
  5. Output to the console requesting a lowercase ‘y’.
  6. Take user input
  7. Assign the user input to the yesNo variable.
  8. Repeat 3-7 until a lowercase ‘y’ occurs.

Input / Output

Please enter a lower case "y" and press enter
n
Please enter a lower case "y" and press enter
Y
Please enter a lower case "y" and press enter
y

The first line is output, then the next is input, and this repeats until the condition is no longer met.

Do While Loop – C# Beginners – Loops

The do-while loop is a particular form of the while loop that will execute the code block once before it starts to check the conditional. Unlike the examples above, the following combines the declare and assign stages. Typically, we declare and assign variables in one line. However, it is vital to recognise that they are separate stages during compilation.

Flowchart

Do While Loop FlowChart
Do While Loop FlowChart

Code

string? yesNo;

do
{
    Console.WriteLine("Please enter a lowercase \"y\" ");
    yesNo = Console.ReadLine();
} while (yesNo != "y");

Output

string? yesNo;

do
{
    Console.WriteLine("Please enter a lowercase \"y\" ");
    yesNo = Console.ReadLine();
} while (yesNo != "y");

Description

This code works the same way as the while loop above, except it runs the code block once regardless of the initial yes-no value.

Video Version – C# Beginners – Loops

Related Articles – C# Beginners – Loops

Related Post

4 thoughts on “C# Beginners – Loops

Leave a Reply

Your email address will not be published. Required fields are marked *