Skip to main content

06. Loops in C#

Level: Beginner

ℹ️ What You'll Learn
  • What a loop is
  • Use for when count is known
  • Use foreach to read arrays/lists
  • Use while when count is unknown
  • Use do while for menus
  • Use break and continue
  • 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

LoopUse When
forYou know how many times to repeat
foreachYou want to read each item in a collection
whileYou do not know the count, repeat while condition is true
do whileCode 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);
}
PartMeaning
int i = 1Start value
i <= 5Continue 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

NeedUse
Need index numberfor
Need to change array valuesfor
Only read each itemforeach
Cleaner code for listsforeach

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

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
string[] students = { "Sahasra", "Priya", "Arjun", "Sneha", "Kiran" };
bool[] present = { true, true, false, true, false };

int presentCount = 0;
int absentCount = 0;

Console.WriteLine("=== Daily Attendance ===");

for (int i = 0; i < students.Length; i++)
{
string status = present[i] ? "Present" : "Absent";
Console.WriteLine($"{i + 1}. {students[i]} - {status}");

if (present[i])
{
presentCount++;
}
else
{
absentCount++;
}
}

double attendancePercentage = (double)presentCount / students.Length * 100;

Console.WriteLine($"Present: {presentCount}");
Console.WriteLine($"Absent: {absentCount}");
Console.WriteLine($"Attendance: {attendancePercentage:F2}%");

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

SituationBest Loop
Print roll numbers 1 to 40for
Read all student namesforeach
Ask until valid inputwhile
Show menu at least oncedo while
Stop after finding itembreak
Skip failed markscontinue

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:

  1. Add more students to array: "Sneha", "Kiran"
  2. Change attendance values: all false or all true
  3. Run and see counts change automatically
  4. Create your own loop: count students with attendance >= 75%

See how loops automate repeated work for many items.


ℹ️ Video Tutorial

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

  1. Use for when count/index is important.
  2. Use foreach when reading all items.
  3. Use while for unknown repetition.
  4. Use do while for menus.
  5. Always make sure a loop can stop.
  6. Use clear variable names like studentIndex.
  7. Keep loop body short and readable.
  8. 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

QuestionAnswer
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

🎯 Q1: What is a loop in C#?

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);
}
🎯 Q2: What is the difference between for and foreach?

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);
}
🎯 Q3: What is the difference between while and do while?

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.

🎯 Q4: What is an infinite loop?

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.

🎯 Q5: What is the difference between break and continue?

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);
}
🎯 Q6: When do we use nested loops?

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 AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

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.

Next Article

Methods in C# ->

nexcoding.in