푸터 콘텐츠로 바로가기
.NET 도움말

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 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
}
for (initialization; condition; increment)
{
    // Loop body
}
$vbLabelText   $csharpLabel

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

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

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}");
    }
}
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 2; j++)
    {
        Console.WriteLine($"i: {i}, j: {j}");
    }
}
$vbLabelText   $csharpLabel

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!");
}
// This is an example of an infinite loop
for (int i = 0; ; i++)
{
    Console.WriteLine("This loop will run forever!");
}
$vbLabelText   $csharpLabel

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

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);
}
for (int i = 0; i < 10 && i != 5; i++)
{
    Console.WriteLine(i);
}
$vbLabelText   $csharpLabel

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

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:

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;
using IronPdf;
using System.IO;
$vbLabelText   $csharpLabel

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

Call the GenerateReport method from your Program.cs file:

GenerateReport();
GenerateReport();
$vbLabelText   $csharpLabel

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.

자주 묻는 질문

C#에서 for 루프는 어떻게 작동하나요?

C#의 for 루프는 코드 블록을 지정된 횟수만큼 반복적으로 실행하는 데 사용됩니다. 루프의 실행을 제어하는 초기화, 조건, 증가의 세 가지 주요 부분으로 구성됩니다.

C#에서 '정적 보이드 메인' 메서드의 역할은 무엇인가요?

'정적 보이드 메인' 메서드는 C# 애플리케이션의 진입점 역할을 합니다. 프로그램이 실행을 시작하는 곳이며 다양한 작업을 수행하는 루프와 같은 초기 코드가 포함되는 경우가 많습니다.

루프를 사용하여 C#에서 PDF 보고서를 생성하려면 어떻게 해야 하나요?

IronPDF와 같은 라이브러리를 사용하여 C#으로 PDF 보고서를 생성할 수 있습니다. 루프를 사용하여 데이터를 처리하고 테이블이나 보고서로 서식을 지정한 다음 IronPDF를 사용하여 PDF 문서로 렌더링할 수 있습니다.

중첩 루프란 무엇이며 C#에서 어떻게 작동하나요?

C#의 중첩 루프는 다른 루프 안에 배치된 루프를 말합니다. 중첩 루프는 여러 요소의 조합에 대한 연산을 수행할 수 있으므로 다차원 데이터 구조를 처리하는 데 특히 유용합니다.

C#에서 무한 루프를 어떻게 방지할 수 있나요?

무한 루프를 방지하려면 루프 조건이 결국 거짓이 되도록 하세요. 특정 조건이 충족되면 루프를 종료하려면 'break'와 같은 루프 제어 문을 활용하세요.

C# 루프에서 'break' 및 'continue' 문은 어떤 용도로 사용되나요?

C#에서 'break' 문은 루프를 즉시 종료하는 데 사용되는 반면, 'continue' 문은 현재 반복을 건너뛰고 루프의 다음 반복을 진행합니다.

For 루프에서 부울 표현식은 어떻게 작동하나요?

루프에 대한 부울 표현식은 루프가 계속 실행되어야 하는지 여부를 결정합니다. 각 반복 전에 평가되며 루프가 계속 진행되려면 참을 반환해야 합니다.

루프와 함께 사용할 C# 라이브러리는 어떻게 설치하나요?

Visual Studio의 패키지 관리자 콘솔을 통해 적절한 설치 명령을 사용하여 C# 라이브러리를 설치하면 루프 내에서 해당 기능을 활용할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.