What are Loops?
Loops allow you to execute code repeatedly. Instead of writing the same code multiple times, you can use a loop.
While Loop
The while loop executes code as long as a condition is true.
Syntax
while (condition)
{
// Code to execute
// Must update condition variable to avoid infinite loop
}
How It Works
- Check condition
- If true, execute code block
- Repeat from step 1
- If false, exit loop
Example 1: Count from 1 to 5
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++; // IMPORTANT! Update counter
}
// Output:
// 1
// 2
// 3
// 4
// 5
Example 2: Sum of Numbers
int iSum = 0;
int iNumber = 1;
while (iNumber <= 10)
{
iSum += iNumber;
iNumber++;
}
Console.WriteLine("Sum: " + iSum); // Sum: 55
Example 3: User Input Validation
int iAge = -1;
while (iAge < 0 || iAge > 120)
{
Console.Write("Enter valid age (0-120): ");
iAge = int.Parse(Console.ReadLine());
if (iAge < 0 || iAge > 120)
{
Console.WriteLine("Invalid age! Try again.\n");
}
}
Console.WriteLine($"Valid age entered: {iAge}");
Do-While Loop
The do-while loop executes code at least once, then checks the condition.
Syntax
do
{
// Code to execute (runs at least once)
} while (condition);
Key Difference: While vs Do-While
While Loop: - Checks condition FIRST - May never execute if condition is false
Do-While Loop: - Executes code FIRST - Always runs at least once - Then checks condition
Example 1: Basic Do-While
int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i <= 5);
// Output:
// 1
// 2
// 3
// 4
// 5
Example 2: Menu System
int iChoice;
do
{
Console.WriteLine("\n=== Menu ===");
Console.WriteLine("1. Add");
Console.WriteLine("2. Subtract");
Console.WriteLine("3. Exit");
Console.Write("Choose option: ");
iChoice = int.Parse(Console.ReadLine());
switch (iChoice)
{
case 1:
Console.WriteLine("Addition selected");
break;
case 2:
Console.WriteLine("Subtraction selected");
break;
case 3:
Console.WriteLine("Exiting...");
break;
default:
Console.WriteLine("Invalid option");
break;
}
} while (iChoice != 3);
Practical Examples from Course
Example 1: Input Validation with TryParse (From Worksheet 2)
using System;
namespace InputValidation
{
class Program
{
static void Main(string[] args)
{
double dNumber;
bool isValid;
do
{
Console.Write("Enter a number: ");
isValid = double.TryParse(Console.ReadLine(), out dNumber);
if (!isValid)
{
Console.WriteLine("\nInvalid input. Please enter a valid number.\n");
}
} while (!isValid);
Console.WriteLine($"\nYou entered: {dNumber}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 2: Operator Validation (From Worksheet 2)
using System;
namespace OperatorValidation
{
class Program
{
static void Main(string[] args)
{
char cOperator;
bool isValid;
do
{
Console.Write("\nEnter an operator (+, -, *, /): ");
isValid = char.TryParse(Console.ReadLine(), out cOperator) &&
(cOperator == '+' || cOperator == '-' ||
cOperator == '*' || cOperator == '/');
if (!isValid)
{
Console.WriteLine("\nInvalid operator. Please enter +, -, *, or /.");
}
} while (!isValid);
Console.WriteLine($"\nValid operator: {cOperator}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 3: Cylinder Volume Calculator (From Practical Test 2)
using System;
namespace CylinderVolume
{
class Program
{
static void Main(string[] args)
{
double dMax = 100;
double dMin = 1;
Console.WriteLine("Cylinder Volume Calculator");
Console.WriteLine("Enter values between 1 and 100\n");
double dRadius = GetValue("Radius", dMin, dMax);
double dHeight = GetValue("Height", dMin, dMax);
double dVolume = Math.PI * Math.Pow(dRadius, 2) * dHeight;
Console.WriteLine($"\nThe Volume is: {dVolume:0.00}");
Console.Write("\n\nPress any key to exit...");
Console.ReadKey();
}
static double GetValue(string sPrompt, double dMin, double dMax)
{
double dValue = 0;
do
{
Console.Write($"\nEnter {sPrompt}: ");
if (!double.TryParse(Console.ReadLine(), out dValue))
{
Console.WriteLine("Invalid input");
dValue = dMax + 1; // Force loop to continue
}
else if (dValue < dMin || dValue > dMax)
{
Console.WriteLine($"Value must be between {dMin} and {dMax}");
}
} while (dValue < dMin || dValue > dMax);
return dValue;
}
}
}
Example 4: Number Statistics Accumulator (From Worksheet 6)
using System;
namespace NumberAccumulator
{
class Program
{
static void Main(string[] args)
{
int iSum = 0;
int iCount = 0;
double dAverage;
do
{
int iNum = GetInt($"Enter integer {iCount + 1} (1-20): ");
iCount++;
iSum += iNum;
dAverage = (double)iSum / iCount;
Console.WriteLine($"\nCurrent Sum: {iSum}");
Console.WriteLine($"Current Average: {dAverage:0.00}\n");
} while (iSum <= 100);
Console.WriteLine("\nThe sum now exceeds 100 and therefore the application will exit.");
Console.Write("\nPress any key to exit...");
Console.ReadKey();
}
static int GetInt(string sPrompt)
{
int iValue;
bool isValid;
do
{
Console.Write(sPrompt);
isValid = int.TryParse(Console.ReadLine(), out iValue);
if (!isValid || iValue < 1 || iValue > 20)
{
Console.WriteLine("Invalid input. Please enter a number between 1 and 20.\n");
isValid = false;
}
} while (!isValid);
return iValue;
}
}
}
Defensive Programming with TryParse
Why Use TryParse?
TryParse
safely converts strings to numbers without throwing exceptions.
Without TryParse (Risky):
Console.Write("Enter age: ");
int iAge = int.Parse(Console.ReadLine()); // Crashes if invalid input!
With TryParse (Safe):
Console.Write("Enter age: ");
bool isValid = int.TryParse(Console.ReadLine(), out int iAge);
if (isValid)
{
Console.WriteLine("Valid age: " + iAge);
}
else
{
Console.WriteLine("Invalid input!");
}
TryParse in Loops
int iNumber;
bool isValid;
do
{
Console.Write("Enter a positive number: ");
isValid = int.TryParse(Console.ReadLine(), out iNumber);
if (!isValid)
{
Console.WriteLine("Error: Not a valid number!\n");
}
else if (iNumber <= 0)
{
Console.WriteLine("Error: Number must be positive!\n");
isValid = false;
}
} while (!isValid);
Console.WriteLine($"You entered: {iNumber}");
Infinite Loops
What is an Infinite Loop?
A loop that never stops because the condition never becomes false.
Example of Infinite Loop (WRONG!)
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
// Missing i++! Loop never ends!
}
How to Avoid Infinite Loops
✅ Always update the loop control variable ✅ Make sure condition can become false ✅ Use break statement if needed
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++; // IMPORTANT! Updates counter
}
Intentional Infinite Loop with Break
while (true)
{
Console.Write("Enter command (or 'exit' to quit): ");
string sCommand = Console.ReadLine();
if (sCommand == "exit")
{
break; // Exit loop
}
Console.WriteLine($"You entered: {sCommand}");
}
Break and Continue
Break Statement
Exits the loop immediately.
int i = 1;
while (i <= 10)
{
if (i == 5)
{
break; // Exit loop when i is 5
}
Console.WriteLine(i);
i++;
}
// Output: 1, 2, 3, 4
Continue Statement
Skips the rest of current iteration and goes to next iteration.
int i = 0;
while (i < 10)
{
i++;
if (i % 2 == 0)
{
continue; // Skip even numbers
}
Console.WriteLine(i);
}
// Output: 1, 3, 5, 7, 9
Practice Exercises
Exercise 1: Countdown
Write a program that counts down from 10 to 1, then prints "Blast off!"
Exercise 2: Password Validator
Create a login system: - Keep asking for password until correct - Password is "secret123" - After 3 failed attempts, lock account
Exercise 3: Sum Calculator
Keep asking user for numbers until they enter 0. Display the sum of all entered numbers.
Exercise 4: Guessing Game
- Generate random number 1-100
- User keeps guessing
- Give hints: "Too high" or "Too low"
- Count number of attempts
Common Mistakes to Avoid
❌ Forgetting to update loop variable:
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
// Missing i++! Infinite loop!
}
✅ Correct:
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
❌ Using = instead of ==:
while (i = 5) // WRONG! Assignment, not comparison
{
Console.WriteLine(i);
}
✅ Correct:
while (i == 5)
{
Console.WriteLine(i);
}
❌ Semicolon after while:
while (i <= 5); // WRONG! Semicolon creates empty loop
{
Console.WriteLine(i);
i++;
}
✅ Correct:
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
While vs Do-While Comparison
Example: Number May Be Too Large
// While loop
int iX = 10;
while (iX < 5)
{
Console.WriteLine(iX); // Never executes!
iX++;
}
// Do-while loop
int iY = 10;
do
{
Console.WriteLine(iY); // Executes once!
iY++;
} while (iY < 5);
When to Use Which?
Use While Loop When: ✅ Condition should be checked before first execution ✅ Loop may not need to run at all
Use Do-While Loop When: ✅ Code must run at least once ✅ Common for input validation and menus
Key Takeaways
✅ While loop checks condition first ✅ Do-while loop executes code first, then checks condition ✅ Do-while always runs at least once ✅ Always update loop control variable to avoid infinite loops ✅ Use TryParse for safe input validation ✅ Break exits the loop immediately ✅ Continue skips to next iteration ✅ Perfect for input validation and menus
Next Topic: C# For Loops