C# Loop Examples: Easy and Practical code Examples in C#
Hey there, coding buddy! π Ready to dive into the world of C# loop examples? Loops are like magic tools in programmingβthey help you repeat tasks without writing the same code over and over. Imagine having to print numbers from 1 to 100 manually… Sounds tiring, right? π Thatβs where loops come to the rescue! π¦ΈββοΈ
In this lesson, youβll explore various loop examples in C# like for
, foreach
, while
, and even advanced ones like Parallel.For
. Don’t worry, Iβll keep things simple, fun, and easy to understand. Plus, youβll find real-world examples that you can actually relate to. So, how about we get started? π
π 1. For Loop
π Question:
Write a program to print numbers from 1 to 5 using a for
loop.
π‘ Hint:
- Use a loop that starts at 1 and ends at 5.
- Increment the counter by 1 each time.
β Solution:
using System;
class Program {
static void Main() {
for (int i = 1; i <= 5; i++) {
Console.WriteLine(i);
}
}
}
π Code Explanation:
int i = 1
: Start from 1.i <= 5
: Run untili
is 5.i++
: Increasei
by 1 each loop.
β‘οΈ Output:
1
2
3
4
5
π 2. Foreach Loop
π Question:
Print all items in the array: { "Apple", "Banana", "Cherry" }
using a foreach
loop.
π‘ Hint:
- Use
foreach
to go through each element.
β Solution:
using System;
class Program {
static void Main() {
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
}
}
π Code Explanation:
foreach (string fruit in fruits)
: Loops through each item infruits
.
β‘οΈ Output:
Apple
Banana
Cherry
π 3. While Loop
π Question:
Print numbers 1 to 3 using a while
loop.
π‘ Hint:
- Initialize a variable.
- Run the loop until the variable reaches 3.
β Solution:
using System;
class Program {
static void Main() {
int i = 1;
while (i <= 3) {
Console.WriteLine(i);
i++;
}
}
}
π Code Explanation:
- Starts at 1, prints it, then increments until
i
> 3.
β‘οΈ Output:
1
2
3
π 4. Do-While Loop
π Question:
Print numbers 1 to 3 using a do-while
loop.
π‘ Hint:
- This loop runs at least once even if the condition is false.
β Solution:
using System;
class Program {
static void Main() {
int i = 1;
do {
Console.WriteLine(i);
i++;
} while (i <= 3);
}
}
π Code Explanation:
- Executes code block first, checks condition later.
β‘οΈ Output:
1
2
3
β‘ 5. Parallel.For Loop (For Multithreading)
π Question:
Use Parallel.For
to print numbers 1 to 5 faster.
π‘ Hint:
- Add
using System.Threading.Tasks;
Parallel.For
runs iterations concurrently.
β Solution:
using System;
using System.Threading.Tasks;
class Program {
static void Main() {
Parallel.For(1, 6, i => {
Console.WriteLine($"Number: {i}");
});
}
}
π Code Explanation:
- Runs iterations simultaneously for speed.
β‘οΈ Output:
Number: 3
Number: 1
Number: 5
Number: 2
Number: 4
β‘ 6. Parallel.ForEach Loop
π Question:
Use Parallel.ForEach
to print an array of colors: { "Red", "Green", "Blue" }
.
π‘ Hint:
- Similar to
foreach
, but runs items in parallel.
β Solution:
using System;
using System.Threading.Tasks;
class Program {
static void Main() {
string[] colors = { "Red", "Green", "Blue" };
Parallel.ForEach(colors, color => {
Console.WriteLine(color);
});
}
}
π Code Explanation:
- Each item is processed in parallel, speeding up execution.
β‘οΈ Output:
Red
Green
Blue
π 7. Goto Loop (Use with caution!)
π Question:
Print numbers 1 to 3 using goto
.
π‘ Hint:
goto
jumps to a labeled section of code.
β Solution:
using System;
class Program {
static void Main() {
int i = 1;
start:
if (i <= 3) {
Console.WriteLine(i);
i++;
goto start;
}
}
}
π Code Explanation:
- Not recommended for general use, but useful in certain cases.
β‘οΈ Output:
1
2
3
π 8. Recursion (Functions calling themselves!)
π Question:
Create a recursive method to print numbers 1 to 3.
π‘ Hint:
- Call the same method inside itself with a changed parameter.
- Always have a base case to stop recursion!
β Solution:
using System;
class Program {
static void PrintNumbers(int n) {
if (n > 3) return; // Base case
Console.WriteLine(n);
PrintNumbers(n + 1); // Recursive call
}
static void Main() {
PrintNumbers(1);
}
}
π Code Explanation:
- Calls
PrintNumbers
untiln
> 3.
β‘οΈ Output:
1
2
3
π Conclusion
Woohoo! π You made it through the world of loops! Feeling like a coding wizard yet? π§ββοΈβ¨ Loops are a huge part of programming, and now you know how to use them to make your code shorter, faster, and more powerful. From the simple for loop to the brainy recursion, youβve tackled them all. High five! π
Remember, loops are all about repetition with purpose. So, keep practicing and youβll get better and faster at spotting when to use which loop. You’ve got this! πͺ
π Next What?
Alright, rockstar! π Youβve just mastered the basics of loops. But waitβitβs time for a challenge! In the next lesson, youβll get to practice some cool coding exercises on loops. π― Yep, youβll solve real-world problems, write your own code, and feel super accomplished. How exciting is that? π
So, are you ready to put those looping skills to the test? Grab your favorite drink β, fire up your code editor, and letβs get coding in the next chapter! π