06. Loops in C#
Level: Beginner
- What a loop is
- Use
forwhen count is known - Use
foreachto read arrays/lists - Use
whilewhen count is unknown - Use
do whilefor menus - Use
breakandcontinue - Practice with marks, attendance, and menu examples
In the previous article, you learned how code makes decisions.
Now we learn how code repeats work.
Example:
Console.WriteLine("Student 1");
Console.WriteLine("Student 2");
Console.WriteLine("Student 3");
Writing repeated lines manually is not good.
Use a loop.
for (int i = 1; i <= 3; i++)
{
Console.WriteLine($"Student {i}");
}
The Problem: How Do We Repeat Tasks?
In a School Management System, we often repeat tasks:
- Print roll numbers from 1 to 40
- Display all student names
- Add marks for all subjects
- Count present and absent students
- Show menu until user chooses Exit
Loops help us repeat code without writing the same code again and again.
What is a Loop?
A loop repeats a block of code.
Start
|
Check condition
|
Run code
|
Repeat until condition becomes false
Loop Types
| Loop | Use When |
|---|---|
for | You know how many times to repeat |
foreach | You want to read each item in a collection |
while | You do not know the count, repeat while condition is true |
do while | Code must run at least once |
Quick Definitions
- Loop - Code that repeats until condition becomes false
- Iteration - One time through the loop
- Condition - Statement that is true or false (loop checks it)
- Array - List of items in order. Example:
int[] marks = { 78, 92, 45 }; - Collection - Group of items (array, list, etc.)
- Break - Statement stopping loop immediately
- Continue - Statement skipping current iteration, moving to next
- Infinite loop - Loop that never stops (mistake to avoid)
What is an Array? (Used in Loops)
An array stores multiple values.
int[] marks = { 78, 92, 45, 88 };
string[] students = { "Sahasra", "Priya", "Arjun" };
Access items by position:
int firstMark = marks[0]; // 78
string firstStudent = students[0]; // "Sahasra"
Why arrays with loops? Use foreach to read all items automatically.
Step 1: for Loop
Use for when you know the count.
Example: print roll numbers 1 to 5.
for (int roll = 1; roll <= 5; roll++)
{
Console.WriteLine($"Roll Number: {roll}");
}
Output:
Roll Number: 1
Roll Number: 2
Roll Number: 3
Roll Number: 4
Roll Number: 5
Understand for Loop
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
| Part | Meaning |
|---|---|
int i = 1 | Start value |
i <= 5 | Continue while this is true |
i++ | Increase by 1 after each round |
{ } | Code that repeats |
Step 2: Calculate Total Marks Using for
int[] marks = { 82, 91, 78, 85, 88 };
int total = 0;
for (int i = 0; i < marks.Length; i++)
{
total += marks[i];
}
double percentage = (double)total / 500 * 100;
Console.WriteLine($"Total: {total}");
Console.WriteLine($"Percentage: {percentage:F2}");
Important:
Array index starts from 0.
marks.Length gives total number of items.
Use i < marks.Length, not i <= marks.Length.
Step 3: foreach Loop
Use foreach when you want to read each item.
string[] students = { "Sahasra", "Priya", "Arjun" };
foreach (string student in students)
{
Console.WriteLine(student);
}
Output:
Sahasra
Priya
Arjun
foreach is simpler than for when you do not need the index.
for vs foreach
| Need | Use |
|---|---|
| Need index number | for |
| Need to change array values | for |
| Only read each item | foreach |
| Cleaner code for lists | foreach |
Example with foreach:
int[] marks = { 82, 91, 78, 85, 88 };
int total = 0;
foreach (int mark in marks)
{
total += mark;
}
Console.WriteLine($"Total: {total}");
Step 4: while Loop
Use while when you do not know how many times the loop should run.
Example: keep asking until valid marks are entered.
int marks = -1;
while (marks < 0 || marks > 100)
{
Console.Write("Enter marks between 0 and 100: ");
string input = Console.ReadLine() ?? "";
int.TryParse(input, out marks);
if (marks < 0 || marks > 100)
{
Console.WriteLine("Invalid marks. Try again.");
}
}
Console.WriteLine($"Valid marks: {marks}");
Important:
while checks condition before running.
If condition is false at the start, loop may not run.
Step 5: do while Loop
Use do while when code must run at least once.
This is common for menus.
int choice;
do
{
Console.WriteLine("=== School Menu ===");
Console.WriteLine("1. Add Student");
Console.WriteLine("2. View Students");
Console.WriteLine("0. Exit");
Console.Write("Enter choice: ");
int.TryParse(Console.ReadLine(), out choice);
if (choice == 1)
{
Console.WriteLine("Add Student selected.");
}
else if (choice == 2)
{
Console.WriteLine("View Students selected.");
}
else if (choice == 0)
{
Console.WriteLine("Exiting...");
}
else
{
Console.WriteLine("Invalid choice.");
}
} while (choice != 0);
Important:
do while runs once first.
Then it checks the condition.
Step 6: break
break stops the loop immediately.
Example: find first failed mark.
int[] marks = { 78, 45, 92, 31, 88 };
foreach (int mark in marks)
{
if (mark < 35)
{
Console.WriteLine($"First failed mark: {mark}");
break;
}
}
Use break when:
- You found what you need
- User selected Exit
- Continuing is not needed
Step 7: continue
continue skips the current round and moves to the next round.
Example: print only passed marks.
int[] marks = { 78, 22, 92, 31, 88 };
foreach (int mark in marks)
{
if (mark < 35)
{
continue;
}
Console.WriteLine($"Passed mark: {mark}");
}
Output:
Passed mark: 78
Passed mark: 92
Passed mark: 88
Full Example: Attendance Report
Expected output:
=== Daily Attendance ===
1. Sahasra - Present
2. Priya - Present
3. Arjun - Absent
4. Sneha - Present
5. Kiran - Absent
Present: 3
Absent: 2
Attendance: 60.00%
Nested Loops
A nested loop means a loop inside another loop.
Example: classes and subjects.
for (int classNumber = 1; classNumber <= 3; classNumber++)
{
Console.WriteLine($"Class {classNumber}");
for (int subjectNumber = 1; subjectNumber <= 4; subjectNumber++)
{
Console.WriteLine($" Subject {subjectNumber}");
}
}
Output:
Class 1
Subject 1
Subject 2
Subject 3
Subject 4
Class 2
Subject 1
...
Use nested loops only when there is a real nested structure.
Quick Reference
| Situation | Best Loop |
|---|---|
| Print roll numbers 1 to 40 | for |
| Read all student names | foreach |
| Ask until valid input | while |
| Show menu at least once | do while |
| Stop after finding item | break |
| Skip failed marks | continue |
When You'll Use This in SMS
Loops process multiple items. SMS uses loops constantly.
Attendance report:
foreach student in students
print attendance status
Report card generation:
for each subject
calculate marks
determine grade
Menu system:
do
show menu
get choice
process choice
while (choice != exit)
Finding data:
foreach mark in marks
if (mark < 35)
"Found failed mark!"
break
Real impact: Loops process thousands of students, marks, fees. Wrong loop = entire report broken or infinite hang.
Try This Now
Run the attendance report example above. Then experiment:
- Add more students to array:
"Sneha", "Kiran" - Change attendance values: all false or all true
- Run and see counts change automatically
- Create your own loop: count students with attendance >= 75%
See how loops automate repeated work for many items.
For loops, foreach loops, while loops explained with live examples. Video coming soon. Subscribe to NexCoding YouTube for updates.
Common Mistakes
Mistake 1: Infinite loop
Wrong:
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
}
Problem:
i never changes, so condition is always true.
Correct:
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
Mistake 2: Off-by-one error
Wrong:
int[] marks = { 82, 91, 78 };
for (int i = 0; i <= marks.Length; i++)
{
Console.WriteLine(marks[i]);
}
Correct:
for (int i = 0; i < marks.Length; i++)
{
Console.WriteLine(marks[i]);
}
Mistake 3: Forgetting that array index starts at 0
string[] students = { "Sahasra", "Priya", "Arjun" };
Console.WriteLine(students[0]); // Sahasra
Console.WriteLine(students[1]); // Priya
Console.WriteLine(students[2]); // Arjun
Mistake 4: Using foreach when index is needed
If you need serial number, use for.
for (int i = 0; i < students.Length; i++)
{
Console.WriteLine($"{i + 1}. {students[i]}");
}
Mistake 5: Making loops too complex
If a loop becomes hard to read, split the logic into smaller steps. You will learn methods in the next article.
Best Practices
- Use
forwhen count/index is important. - Use
foreachwhen reading all items. - Use
whilefor unknown repetition. - Use
do whilefor menus. - Always make sure a loop can stop.
- Use clear variable names like
studentIndex. - Keep loop body short and readable.
- Avoid deep nested loops as a beginner.
Practice Task
Create a marks report for 5 subjects.
Data:
int[] marks = { 80, 75, 90, 60, 85 };
Tasks:
- Print each mark with subject number.
- Calculate total marks.
- Calculate percentage.
- Print pass/fail using percentage >= 35.
Starter:
int[] marks = { 80, 75, 90, 60, 85 };
int total = 0;
for (int i = 0; i < marks.Length; i++)
{
Console.WriteLine($"Subject {i + 1}: {marks[i]}");
total += marks[i];
}
double percentage = (double)total / 500 * 100;
string result = percentage >= 35 ? "Pass" : "Fail";
Console.WriteLine($"Total: {total}");
Console.WriteLine($"Percentage: {percentage:F2}");
Console.WriteLine($"Result: {result}");
Quick Revision
| Question | Answer |
|---|---|
| What does a loop do? | Repeats code |
| Which loop is best when count is known? | for |
| Which loop reads every item in a collection? | foreach |
| Which loop checks condition before running? | while |
| Which loop runs at least once? | do while |
What does break do? | Stops the loop |
What does continue do? | Skips current round |
A loop repeats a block of code while a condition is true or while items are available.
Example:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
Use for when you need index or exact count control.
Use foreach when you only want to read each item.
Example:
for (int i = 0; i < marks.Length; i++)
{
Console.WriteLine(marks[i]);
}
foreach (int mark in marks)
{
Console.WriteLine(mark);
}
while checks the condition before running.
do while runs once first, then checks the condition.
Use do while for menus because the menu must appear at least once.
An infinite loop never stops because the condition never becomes false.
Example:
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
}
Here i is never increased, so the loop continues forever.
break stops the loop completely.
continue skips only the current round and moves to the next round.
Example:
foreach (int mark in marks)
{
if (mark < 35)
{
continue;
}
Console.WriteLine(mark);
}
Use nested loops when data has a nested structure.
Example:
Classes
Subjects
Code:
for (int classNumber = 1; classNumber <= 3; classNumber++)
{
for (int subjectNumber = 1; subjectNumber <= 4; subjectNumber++)
{
Console.WriteLine($"Class {classNumber}, Subject {subjectNumber}");
}
}
Use ChatGPT, Claude, or Copilot to go deeper on C# loops. Try these prompts:
"Explain for, foreach, while, and do while using school examples""Give me 10 loop practice questions for marks and attendance""Explain break and continue with simple examples""Quiz me with 5 beginner questions about C# loops"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.