IRONSOFTWAREHOME
.NET HELP

C# For Loop (How it Works for Developers)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: August 1, 2026

In this comprehensive tutorial, we'll cover everything you need to know to get started with for loops within the public static void Main method. We'll explore for loops, 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
}

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 the first for loop!");
        }
    }
}

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 Loops

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 an inner loop inside an outer loop in C#:

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

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 loops or foreach loops to ensure that the exit condition will eventually be met. The following is an example of an 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!");
}

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}");
}

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 expression 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);
}

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}");
}

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

Learn about IronPDF's PDF generation capabilities to create dynamic and robust PDF reports 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:

PM > Install-Package IronPdf

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

Step 1: Add the necessary namespaces.

using IronPdf;
using System.IO;

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 IronPdf
    var pdf = new IronPdf.ChromePdfRenderer();
    var document = pdf.RenderHtmlAsPdf(finalHtml);

    // Save the PDF to a file
    document.SaveAs("NumberSquaresReport.pdf");
}

Call the GenerateReport method from your Program.cs file:

GenerateReport();

Number Squares Report from IronPDF

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 of IronPDF for you to test its capabilities, and if you find it useful, licensing starts from affordable options suited for your needs.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

OR
bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999