Counting and Looping
A loop is a type of conditional statement that keeps checking a condition and executing a statement until the condition is false.
Introduction#
A loop is a kind of conditional statement that repeatedly checks a condition and keeps executing a statement until that condition becomes false.
while a Condition is True#
One of the operators used to perform a loop is called while. To create a while loop:
- Use the following formula: while ( Condition ) Statement ;
- Right-click the section where you want to add it and click Insert Snippet... Double-click Visual C#. In the list, double-click while
To run a while condition, the compiler first evaluates the Condition. If the Condition is true, it executes the Statement, then checks the Condition again. As long as the Condition stays true, the Statement continues to run. When the Condition turns false, the loop ends.
Here is an example:
using System;
public class Exercise
{
public static int Main()
{
var stories = 0;
while( stories <= 4 )
{
Console.WriteLine("Number {0}", stories);
stories++;
}
return 0;
}
}This would produce:
Number 0
Number 1
Number 2
Number 3
Number 4
Press any key to continue . . .To effectively execute a while condition, you should make sure you provide a mechanism for the compiler to use or get a reference value for the condition, variable, or expression being checked. This is sometimes in the form of a variable being initialized although it could be some other expression. Such a while condition could be illustrated as follows:
do This while a Condition is True#
The while loop is used to first check a condition and then execute a statement. If the condition is false, the statement would never execute. Consider the following program:
using System;
public class Exercise
{
public static int Main()
{
var stories = 5;
while (stories <= 4)
{
Console.WriteLine("Number {0}", stories);
stories++;
}
return 0;
}
}When this program executes, nothing from the while loop would execute because, as the condition is checked in the beginning, it is false and the compiler would not get to the Statement. In some cases, you may want to execute a statement before checking the condition for the first time. This can be done using the do...while statement. Its formula is:
do Statement while (Condition);The do...while condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop. If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole do...while statement must end with a semicolon.
Another version of the counting program seen previously would be:
using System;
public class Exercise
{
public static int Main()
{
var stories = 0;
do
Console.WriteLine("Number {0}", stories++);
while (stories <= 4);
return 0;
}
}This would produce:
Number 0
Number 1
Number 2
Number 3
Number 4
Press any key to continue . . .If the Statement is long and should span more than one line, start it with an opening curly bracket "{" and end it with a closing curly bracket "}". Application: Introducing Counting and Looping
- Start Microsoft Visual Studio
- To create a new program, on the main menu, click File -> New Project...
- In the middle list, click Empty Project
- Change the Name to FlowerShop3
- To create a new class, on the main menu, click Project -> Add Class...
- Set the Name to Flower and click Add
- Complete the Flower.cs file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FlowerShop2 { public enum FlowerType { Roses = 1, Lilies, Daisies, Carnations, LivePlant, Mixed } public enum FlowerColor { Red = 1, White, Yellow, Pink, Orange, Blue, Lavender, Mixed } public enum FlowerArrangement { Bouquet = 1, Vase, Basket, Any } public class Flower { public FlowerType typeOfFlower; public FlowerColor majorColor; public FlowerArrangement arrangement; public decimal unitPrice; public Flower() { typeOfFlower = FlowerType.Mixed; majorColor = FlowerColor.Mixed; arrangement = FlowerArrangement.Vase; unitPrice = 0.00M; } public Flower(FlowerType type) { typeOfFlower = type; majorColor = FlowerColor.Mixed; arrangement = FlowerArrangement.Vase; unitPrice = 0.00M; } public Flower(FlowerType type, FlowerColor color, FlowerArrangement argn, decimal price) { typeOfFlower = type; majorColor = color; arrangement = argn; unitPrice = price; } } }
- To create a new class, in the Solution Explorer, right-click the project name, position the mouse on Add and click Class...
- Set the Name of the class to OrderProcessing and click Add
- Complete the OrderProcessing.cs file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FlowerShop3 { public class OrderProcessing { public Flower flowerOrder; public int quantity; public OrderProcessing() { flowerOrder = new Flower(); } public decimal GetTotalPrice() { return quantity * flowerOrder.unitPrice; } public void GetFlowerType() { int choice = 0; do { Console.WriteLine("Enter the Type of Flower Order"); Console.WriteLine("1. Roses"); Console.WriteLine("2. Lilies"); Console.WriteLine("3. Daisies"); Console.WriteLine("4. Carnations"); Console.WriteLine("5. Live Plant"); Console.WriteLine("6. Mixed"); Console.Write("Your Choice: "); choice = int.Parse(Console.ReadLine()); } while ((choice < 1) || (choice > 6)); switch (choice) { case 1: flowerOrder.typeOfFlower = FlowerType.Roses; break; case 2: flowerOrder.typeOfFlower = FlowerType.Lilies; break; case 3: flowerOrder.typeOfFlower = FlowerType.Daisies; break; case 4: flowerOrder.typeOfFlower = FlowerType.Carnations; break; case 5: flowerOrder.typeOfFlower = FlowerType.LivePlant; break; default: flowerOrder.typeOfFlower = FlowerType.Mixed; break; } } public void GetFlowerColor() { int choice = 0; do { Console.WriteLine("Enter the Color"); Console.WriteLine("1. Red"); Console.WriteLine("2. White"); Console.WriteLine("3. Yellow"); Console.WriteLine("4. Pink"); Console.WriteLine("5. Orange"); Console.WriteLine("6. Blue"); Console.WriteLine("7. Lavender"); Console.WriteLine("8. Mixed"); Console.Write("Your Choice: "); choice = int.Parse(Console.ReadLine()); } while ((choice < 1) || (choice > 8)); switch (choice) { case 1: flowerOrder.majorColor = FlowerColor.Red; break; case 2: flowerOrder.majorColor = FlowerColor.White; break; case 3: flowerOrder.majorColor = FlowerColor.Yellow; break; case 4: flowerOrder.majorColor = FlowerColor.Pink; break; case 5: flowerOrder.majorColor = FlowerColor.Yellow; break; case 6: flowerOrder.majorColor = FlowerColor.Blue; break; case 7: flowerOrder.majorColor = FlowerColor.Lavender; break; default: flowerOrder.majorColor = FlowerColor.Mixed; break; } } public void GetFlowerArrangement() { int choice = 0; do { Console.WriteLine("Enter the Type of Arrangement"); Console.WriteLine("1. Bouquet"); Console.WriteLine("2. Vase"); Console.WriteLine("3. Basket"); Console.WriteLine("4. Mixed"); Console.Write("Your Choice: "); choice = int.Parse(Console.ReadLine()); } while ((choice < 1) || (choice > 4)); switch (choice) { case 1: flowerOrder.arrangement = FlowerArrangement.Bouquet; break; case 2: flowerOrder.arrangement = FlowerArrangement.Vase; break; case 3: flowerOrder.arrangement = FlowerArrangement.Basket; break; default: flowerOrder.arrangement = FlowerArrangement.Any; break; } } public void ProcessOrder() { GetFlowerType(); GetFlowerColor(); GetFlowerArrangement(); Console.Write("Enter the Unit Price: "); flowerOrder.unitPrice = decimal.Parse(Console.ReadLine()); Console.Write("Enter Quantity: "); quantity = int.Parse(Console.ReadLine()); } public void ShowOrder() { Console.WriteLine("======================="); Console.WriteLine("==-=-=Flower Shop=-=-=="); Console.WriteLine("-----------------------"); Console.WriteLine("Flower Type: {0}", flowerOrder.typeOfFlower ); Console.WriteLine("Flower Color: {0}", flowerOrder.majorColor ); Console.WriteLine("Arrangement: {0}", flowerOrder.arrangement); Console.WriteLine("Price: {0:C}", flowerOrder.unitPrice); Console.WriteLine("Quantity: {0}", quantity); Console.WriteLine("Total Price: {0:C}", GetTotalPrice()); Console.WriteLine("======================="); } } }
- To create a new file, on the main menu, click Project -> Add New Item...
- In the middle list, click Code File
- Change the Name FlowerShop and click Add
- Complete the file as follows: using System; using FlowerShop3; public class Program { public static int Main() { OrderProcessing order = new OrderProcessing(); Console.Title = "Corner Stone Flower Shop"; order.ProcessOrder(); Console.Clear(); order.ShowOrder(); System.Console.ReadKey(); return 0; } }
- Execute the application and test it. Here is an example: Enter the Type of Flower Order 1. Roses 2. Lilies 3. Daisies 4. Carnations 5. Live Plant 6. Mixed Your Choice: 8 Enter the Type of Flower Order 1. Roses 2. Lilies 3. Daisies 4. Carnations 5. Live Plant 6. Mixed Your Choice: 2 Enter the Color 1. Red 2. White 3. Yellow 4. Pink 5. Orange 6. Blue 7. Lavender 8. Mixed Your Choice: 9 Enter the Color 1. Red 2. White 3. Yellow 4. Pink 5. Orange 6. Blue 7. Lavender 8. Mixed Your Choice: 0 Enter the Color 1. Red 2. White 3. Yellow 4. Pink 5. Orange 6. Blue 7. Lavender 8. Mixed Your Choice: 7 Enter the Type of Arrangement 1. Bouquet 2. Vase 3. Basket 4. Mixed Your Choice: 8 Enter the Type of Arrangement 1. Bouquet 2. Vase 3. Basket 4. Mixed Your Choice: 5 Enter the Type of Arrangement 1. Bouquet 2. Vase 3. Basket 4. Mixed Your Choice: 2 Enter the Unit Price: 42.85 Enter Quantity: 2
- Press Enter ======================= ==-=-=Flower Shop=-=-== ----------------------- Flower Type: Lilies Flower Color: Lavender Arrangement: Vase Price: $42.85 Quantity: 2 Total Price: $85.70 ======================= Press any key to continue . . .
- Close the DOS window
for#
The for statement is typically used to count a number of items. At its regular structure, it is divided in three parts. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The syntax of the for statement is:
for(Start; End; Frequency) Statement;The Start expression is a variable assigned the starting value. This could be Count = 0; The End expression sets the criteria for ending the counting. An example would be Count < 24; this means the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting. The Frequency expression would let the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count.Here is an example that applies the for statement:
using System;
public class Exercise
{
public static int Main()
{
for (var stories = 0; stories <= 4; stories++)
Console.WriteLine("Number {0}", stories);
return 0;
}
}This would produce:
Number 1
Number 2
Number 3
Number 4
Press any key to continue . . .Previous Copyright © 2010 C# Key Next

