C# For Loop (How it Works for Developers)

In this comprehensive tutorial, we'll cover everything you need to know to get started with for loop within public static void Main method. We'll explore for loop, loop variables, loop bodies, iteration variables, inner and outer loops, infinite loops, boolean expressions, nested loops, and more. Let's get started!

Getting Started with for Loops

A for loop is a type of loop in C#, specifically designed for situations where you know exactly how many times you want to iterate. The syntax for a for loop in C# is shown in the below code block


    for (initialization; condition; increment)
    {
        // Loop body
    }

    for (initialization; condition; increment)
    {
        // Loop body
    }
initialization
Do While condition
		' Loop body
	increment
Loop
VB   C#

Let's break down the components of a for loop:

  1. Initialization: This is where the loop variable, or iteration variable, is declared and initialized.
  2. Condition: A boolean/conditional expression that determines whether the loop should continue executing statements multiple times or not.
  3. Increment: This statement updates the iteration variable after each iteration.

Static Void Main and Loop Variables

In C#, the static void Main method or static void Main(String []args) is the entry point of your application. This is where your program starts executing. Here's a loop example of how to use a for loop inside the static void Main method:


    using System;

    class Program
    {
        static void Main()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("This is first for loop!");
            }
        }
    }

    using System;

    class Program
    {
        static void Main()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("This is first for loop!");
            }
        }
    }
Imports System

	Friend Class Program
		Shared Sub Main()
			For i As Integer = 0 To 4
				Console.WriteLine("This is first for loop!")
			Next i
		End Sub
	End Class
VB   C#

In this example, the loop variable int i is initialized to 0 and acts as the variable. The loop will continue executing as long as i is less than 5. After each iteration, the increment operation i++ increases the value of i by 1.

Exploring Nested Loop

Nested loops are loops that are placed inside other loops, forming an inner loop and an outer loop with iterator sections. These can be useful when working with multidimensional data structures like matrices, or when you need to perform a certain operation on every combination of elements.

Here's an example of a nested for loop with inner loop inside outer loop in C#:


    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            Console.WriteLine($"i: {i}, j: {j}");
        }
    }

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            Console.WriteLine($"i: {i}, j: {j}");
        }
    }
For i As Integer = 0 To 2
		For j As Integer = 0 To 1
			Console.WriteLine($"i: {i}, j: {j}")
		Next j
Next i
VB   C#

In this example, the outer loop executes and starts with i equal to 0. The inner loop then iterates through all possible values of j before moving on to the next value of i.

Infinite Loops and Loop Control

An infinite loop is a loop that never ends because its test condition never becomes false. These can be dangerous, as they can cause your program to hang indefinitely. Be cautious when writing loops such as while loop, foreach loop to ensure that the exit condition will eventually be met. The following is an example of infinite loop with no specified condition in C#.


// This is an example of an infinite loop
for (int i = 0; ; i++)
{
    Console.WriteLine("This loop will run forever!");
}

// This is an example of an infinite loop
for (int i = 0; ; i++)
{
    Console.WriteLine("This loop will run forever!");
}
' This is an example of an infinite loop
Dim i As Integer = 0
Do
	Console.WriteLine("This loop will run forever!")
	i += 1
Loop
VB   C#

In addition to the standard for loop structure, C# also provides loop control statements, such as break and continue, which can help you manage your loops more effectively.

  • break: This statement is used to immediately exit the loop. When a break statement is encountered, the loop terminates, and the program continues with the next line of code outside the loop.
  • continue: This statement is used to skip the remaining code in the loop body for the current iteration and jump to the next iteration of the loop.

Here's an example demonstrating the use of break and continue in a for loop:


for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break; // Exits the loop when i is equal to 5
    }

    if (i % 2 == 0)
    {
        continue; // Skips even numbers
    }

    Console.WriteLine($"Odd number: {i}");
}

for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break; // Exits the loop when i is equal to 5
    }

    if (i % 2 == 0)
    {
        continue; // Skips even numbers
    }

    Console.WriteLine($"Odd number: {i}");
}
For i As Integer = 0 To 9
	If i = 5 Then
		Exit For ' Exits the loop when i is equal to 5
	End If

	If i Mod 2 = 0 Then
		Continue For ' Skips even numbers
	End If

	Console.WriteLine($"Odd number: {i}")
Next i
VB   C#

In this example, the loop stops executing when i reaches 5. The continue statement is used to skip even numbers, so only odd numbers less than 5 will be printed.

Boolean Expressions and Loop Conditions

The loop condition is a boolean that determines whether the loop should continue executing. This expression is evaluated before each iteration, and the loop will only run if the expression is true. Commonly used boolean expressions in many loops include:

  • Comparisons: i < 10, i 10, i >= 10, i == 10, i != 10
  • Logical operators: && (AND), || (OR), ! (NOT)

You can combine multiple expressions using logical operators to create more complex loop conditions. For example:


    for (int i = 0; i < 10 && i != 5; i++)
    {
        Console.WriteLine(i);
    }

    for (int i = 0; i < 10 && i != 5; i++)
    {
        Console.WriteLine(i);
    }
Dim i As Integer = 0
Do While i < 10 AndAlso i <> 5
		Console.WriteLine(i)
	i += 1
Loop
VB   C#

In this example, the loop will execute as long as i is less than 10 and not equal to 5.

Code Blocks and Loop Bodies

A code block is a group of statements enclosed within curly braces {}. In a for loop, the code block that follows the loop declaration is known as the loop body. This is where you'll place the code you want to execute during each iteration of the loop.


    for (int i = 0; i < 5; i++)
    {
        // This is the loop body
        Console.WriteLine($"Iteration: {i}");
    }

    for (int i = 0; i < 5; i++)
    {
        // This is the loop body
        Console.WriteLine($"Iteration: {i}");
    }
For i As Integer = 0 To 4
		' This is the loop body
		Console.WriteLine($"Iteration: {i}")
Next i
VB   C#

In this example, the loop body consists of a single Console.WriteLine statement that prints the current iteration number.

Loop Execution Steps

When a for loop is encountered in your code, the following sequence of events occurs:

  1. The loop variable is initialized.
  2. The boolean expression is evaluated. If the expression is false, the loop is skipped, and the program continues with the next line of code outside the loop.
  3. If the expression is true, the loop body is executed.
  4. The loop variable is incremented or updated.
  5. Steps 2-4 are repeated until the boolean expression becomes false.

Integrating IronPDF for Generating Reports with For Loops

IronPDF is a powerful library for generating, editing, and rendering PDFs in C#. It can be a useful tool when working with for loops, especially if you need to create dynamic reports or documents based on the data processed in your loops. In this section, we'll show you how to use IronPDF in conjunction with C# for loops to generate a simple report.

First, you'll need to install the IronPDF NuGet package. You can do this using the Package Manager Console in Visual Studio:

    Install-Package IronPDF

Once you have IronPDF installed, let's create a simple example that generates a PDF report from HTML containing a table of numbers and their squares using a for loop.

Step 1: Add the necessary namespaces.


    using IronPdf;
    using System.IO;

    using IronPdf;
    using System.IO;
Imports IronPdf
	Imports System.IO
VB   C#

Step 2: Create a new method called GenerateReport.

static void GenerateReport()
{
    // Create an HTML template for the report
    var htmlTemplate = @"
    <html>
        <head>
            <style>
                table {
                    border-collapse: collapse;
                    width: 100%;
                }

                th, td {
                    border: 1px solid black;
                    padding: 8px;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Number Squares Report</h1>
            <table>
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Square</th>
                    </tr>
                </thead>
                <tbody>
                    {0}
                </tbody>
            </table>
        </body>
    </html>";

    // Generate the table rows using a for loop
    string tableRows = "";
    for (int i = 1; i <= 10; i++)
    {
        tableRows += $"<tr><td>{i}</td><td>{i * i}</td></tr>";
    }

    // Insert the generated table rows into the HTML template
    string finalHtml = string.Format(htmlTemplate, tableRows);

    // Create a new PDF document from the HTML using two variables
    var pdf = new IronPdf.ChromePdfRenderer();
    var document = pdf.RenderHtmlAsPdf(finalHtml);

    // Save the PDF to a file
    document.SaveAs("NumberSquaresReport.pdf");
}
static void GenerateReport()
{
    // Create an HTML template for the report
    var htmlTemplate = @"
    <html>
        <head>
            <style>
                table {
                    border-collapse: collapse;
                    width: 100%;
                }

                th, td {
                    border: 1px solid black;
                    padding: 8px;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Number Squares Report</h1>
            <table>
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Square</th>
                    </tr>
                </thead>
                <tbody>
                    {0}
                </tbody>
            </table>
        </body>
    </html>";

    // Generate the table rows using a for loop
    string tableRows = "";
    for (int i = 1; i <= 10; i++)
    {
        tableRows += $"<tr><td>{i}</td><td>{i * i}</td></tr>";
    }

    // Insert the generated table rows into the HTML template
    string finalHtml = string.Format(htmlTemplate, tableRows);

    // Create a new PDF document from the HTML using two variables
    var pdf = new IronPdf.ChromePdfRenderer();
    var document = pdf.RenderHtmlAsPdf(finalHtml);

    // Save the PDF to a file
    document.SaveAs("NumberSquaresReport.pdf");
}
Shared Sub GenerateReport()
	' Create an HTML template for the report
	Dim htmlTemplate = "
    <html>
        <head>
            <style>
                table {
                    border-collapse: collapse;
                    width: 100%;
                }

                th, td {
                    border: 1px solid black;
                    padding: 8px;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Number Squares Report</h1>
            <table>
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Square</th>
                    </tr>
                </thead>
                <tbody>
                    {0}
                </tbody>
            </table>
        </body>
    </html>"

	' Generate the table rows using a for loop
	Dim tableRows As String = ""
	For i As Integer = 1 To 10
		tableRows &= $"<tr><td>{i}</td><td>{i * i}</td></tr>"
	Next i

	' Insert the generated table rows into the HTML template
	Dim finalHtml As String = String.Format(htmlTemplate, tableRows)

	' Create a new PDF document from the HTML using two variables
	Dim pdf = New IronPdf.ChromePdfRenderer()
	Dim document = pdf.RenderHtmlAsPdf(finalHtml)

	' Save the PDF to a file
	document.SaveAs("NumberSquaresReport.pdf")
End Sub
VB   C#

Call the GenerateReport method from your Program.cs file:

GenerateReport();
GenerateReport();
GenerateReport()
VB   C#

Number Squares Report

When you run this example, a PDF report called "NumberSquaresReport.pdf" will be generated in your application's output directory. The report will contain a table of numbers from 1 to 10 and their squares, generated using a C# for loop.

Conclusion

In conclusion, this comprehensive tutorial has provided you with a solid foundation in C# for loops and their related concepts. We've explored loop variables, loop bodies, iteration variables, inner and outer loops, infinite loops, boolean expressions, code blocks, nested loops, and even demonstrated how to integrate the powerful IronPDF library to generate dynamic PDF reports using for loops.

IronPDF offers a free trial for you to test its capabilities, and if you find it useful, licensing starts from $749.