Welcome to this module, Day 4 of 30-Day .NET Challenge: For Loops, where let's dive into the world of for statements. Explore how to write For Loop statements that iterate a set number of times.
The for statement allows you to iterate through a code block a fixed number of times, providing precise control over the iteration process.
To begin, create a static class file called “ForLoop.cs” within the console application. Insert the provided code snippet into this file.
/// <summary>
/// Outputs
/// 0
/// 1
/// 2
/// 3
/// 4
/// 5
/// 6
/// 7
/// 8
/// 9
/// </summary>
public static void ForLoopExample()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
Execute the code from the main method as follows
#region Day 4 - For Loops
ForLoops.ForLoopExample();
#endregion
// Console Output
0
1
2
3
4
5
6
7
8
9
The goal is to iterate through a code block while counting down instead of counting up.
Add another method into the same static class as shown below
/// <summary>
/// Outputs
/// 10
/// 9
/// 8
/// 7
/// 6
/// 5
/// 4
/// 3
/// 2
/// 1
/// 0
/// </summary>
public static void BackwardForLoopExample()
{
for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
}
}
Execute the code from the main method as follows
#region Day 4 - For Loops
ForLoops.BackwardForLoopExample();
#endregion
// Console Output
10
9
8
7
6
5
4
3
2
1
0
The goal is to skip specific values in the iterator variable. Add another method into the same static class as shown below
/// <summary>
/// Outputs
/// 3
/// 6
/// 0
/// 9
/// </summary>
public static void IterationForLoopExample()
{
for (int i = 0; i < 10; i += 3)
{
Console.WriteLine(i);
}
}
Execute the code from the main method as follows
#region Day 4 - For Loops
ForLoops.IterationForLoopExample();
#endregion
// Console Output
0
3
6
9
The goal is to exit the iteration statement prematurely based on some conditions. Add another method into the same static class as shown below
/// <summary>
/// Outputs
/// 0
/// 1
/// 2
/// 3
/// 4
/// 5
/// 6
/// 7
/// </summary>
public static void BreakForLoopExample()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
if (i == 7) break;
}
}
Execute the code from the main method as follows
#region Day 4 - For Loops
ForLoops.BreakForLoopExample();
#endregion
// Console Output
0
1
2
3
4
5
6
7
GitHub — ssukhpinder/30DayChallenge.Net
Thank you for being a part of the C# community! Before you leave:
Follow us: X | LinkedIn | Dev.to | Hashnode | Newsletter | Tumblr
Visit our other platforms: GitHub | Instagram | Tiktok | Quora | Daily.dev
More content at C# Programming
Also published here.