Zum Fußzeileninhalt springen
.NET HILFE

C# Für Schleife (Wie es für Entwickler funktioniert)

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
}
initialization
Do While condition
	' Loop body
	increment
Loop
$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!");
        }
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		For i As Integer = 0 To 4
			Console.WriteLine("This is the first for loop!")
		Next i
	End Sub
End Class
$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}");
    }
}
For i As Integer = 0 To 2
	For j As Integer = 0 To 1
		Console.WriteLine($"i: {i}, j: {j}")
	Next j
Next i
$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!");
}
' This is an example of an infinite loop
Dim i As Integer = 0
Do
	Console.WriteLine("This loop will run forever!")
	i += 1
Loop
$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}");
}
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
$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);
}
Dim i As Integer = 0
Do While i < 10 AndAlso i <> 5
	Console.WriteLine(i)
	i += 1
Loop
$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}");
}
For i As Integer = 0 To 4
	' This is the loop body
	Console.WriteLine($"Iteration: {i}")
Next 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;
Imports IronPdf
Imports 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");
}
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 IronPdf
	Dim pdf = New IronPdf.ChromePdfRenderer()
	Dim document = pdf.RenderHtmlAsPdf(finalHtml)

	' Save the PDF to a file
	document.SaveAs("NumberSquaresReport.pdf")
End Sub
$vbLabelText   $csharpLabel

Call the GenerateReport method from your Program.cs file:

GenerateReport();
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.

Häufig gestellte Fragen

Wie funktioniert eine for-Schleife in C#?

Eine for-Schleife in C# wird verwendet, um einen Codeblock wiederholt für eine festgelegte Anzahl von Wiederholungen auszuführen. Sie besteht aus drei Hauptteilen: Initialisierung, Bedingung und Inkrement, die die Ausführung der Schleife steuern.

Welche Rolle spielt die Methode 'static void Main' in C#?

Die Methode 'static void Main' dient als Einstiegspunkt einer C#-Anwendung. Hier beginnt die Programmausführung und oft enthält sie Anfangscode wie for-Schleifen, um verschiedene Aufgaben auszuführen.

Wie können Sie PDF-Berichte in C# mit for-Schleifen generieren?

Sie können eine Bibliothek wie IronPDF verwenden, um PDF-Berichte in C# zu erzeugen. For-Schleifen können genutzt werden, um Daten zu verarbeiten und in eine Tabelle oder einen Bericht zu formatieren, der dann mit IronPDF als PDF-Dokument gerendert werden kann.

Was sind verschachtelte Schleifen und wie funktionieren sie in C#?

Verschachtelte Schleifen in C# sind Schleifen, die in anderen Schleifen platziert werden. Sie sind besonders nützlich für die Bearbeitung mehrdimensionaler Datenstrukturen, da sie Ihnen ermöglichen, Operationen an Kombinationen von Elementen durchzuführen.

Wie können Sie Endlosschleifen in C# verhindern?

Um Endlosschleifen zu verhindern, stellen Sie sicher, dass die Bedingung Ihrer Schleife schließlich falsch wird. Verwenden Sie Steueranweisungen wie 'break', um die Schleife zu verlassen, wenn eine bestimmte Bedingung erfüllt ist.

Wofür werden die Anweisungen 'break' und 'continue' in C# Schleifen verwendet?

In C# wird die 'break'-Anweisung verwendet, um eine Schleife sofort zu verlassen, während die 'continue'-Anweisung die aktuelle Iteration überspringt und mit der nächsten Iteration der Schleife fortfährt.

Wie funktionieren boolesche Ausdrücke in einer for-Schleife?

Boolesche Ausdrücke in for-Schleifen bestimmen, ob die Schleife weiterhin ausgeführt werden soll. Sie werden vor jeder Iteration ausgewertet und müssen true zurückgeben, damit die Schleife weiter ausgeführt wird.

Wie installieren Sie eine C#-Bibliothek zur Verwendung in Verbindung mit for-Schleifen?

Sie können eine C#-Bibliothek über die Paket-Manager-Konsole in Visual Studio mithilfe des entsprechenden Installationsbefehls installieren, damit Sie deren Funktionen innerhalb von for-Schleifen nutzen können.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen