Seven Things about C#

A beginners tutorial, where each article highlights 7 important things about a specific feature of the C# programming language.

Member-only story

7 Things about C#: Loops

--

Abstract 3D image of different strands of light that curl and loop.

In all of the previous articles in this series, the apps ran one time and then stopped. This is okay if the program is designed to accomplish one task and quit. However, stopping early is a problem when we want our apps to keep running until we ask them to stop.

More generally, computers are good at repetitive tasks like performing a task while a condition is true, iterating for a specific number of times, or performing a task on a list of things. This article explains how to accomplish these tasks with loops.

1 — While Loops Run on True Conditions

The If Statements tutorial discussed conditional expressions and how they are useful for determining whether to run specific logic. In a similar light, conditional expressions are important for determining whether to run specific logic in a loop. Essentially, to run code repeatedly while a condition is true. C# has a statement called a while that does just that and here’s an example:

string choice = "";

while (choice != "Q" && choice != "q")
{
Console.WriteLine("\nDoor Chooser\n");

Console.WriteLine("1 - Door 1");
Console.WriteLine("2 - Door 2");
Console.WriteLine("Q - Quit\n");

Console.Write("Please choose (1, 2, or Q): ");

choice = Console.ReadLine();

Console.WriteLine("\n* You chose '{0}'", choice);
}

--

--

Seven Things about C#
Seven Things about C#

Published in Seven Things about C#

A beginners tutorial, where each article highlights 7 important things about a specific feature of the C# programming language.

Joe Mayo
Joe Mayo

Written by Joe Mayo

Author, Instructor, & Independent Consultant. Author of C# Cookbook: — http://bit.ly/CSharpCookbook — @OReillyMedia #ai #csharp #Web3

No responses yet