For Loop C Sharp Language

For Loop C# Language

For loops are an essential construct in the C# programming language, allowing developers to iterate over a s

equence of elements and perform a specific set of actions for each element. They provide a structured and efficient way to repeat code blocks. In this article, we’ll explore the ins and outs of using for loops in C# with practical examples to help you understand their power and versatility.

The Basic Structure of a For Loop:

A for loop in C# follows a well-defined structure:

for (initialization; condition; increment)
{
    // Code to be repeated
}
  1. Initialization: This part is executed only once, at the beginning of the loop, and is used to declare and initialize loop control variables.
  2. Condition: The loop continues to execute as long as the condition remains true. If the condition becomes false, the loop terminates.
  3. Increment: This step is executed after each iteration of the loop and is typically used to update loop control variables.

Let’s dive into some practical examples to understand how for loops work.

Example 1: Counting from 1 to 10

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine(i);
}

In this example, we use a for loop to count from 1 to 10. The loop control variable i is initialized to 1, and the loop continues as long as i is less than or equal to 10. After each iteration, i is incremented by 1.

Example 2: Iterating Over an Array

int[] numbers = { 5, 10, 15, 20, 25 };
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

In this example, we use a for loop to iterate over an array of numbers. The loop control variable i is used as an index to access each element in the array, starting from index 0 and continuing until it reaches the array’s length.

Example 3: Custom Step Size

You can customize the step size in a for loop by changing the increment part. For example, to print even numbers from 2 to 20, you can use the following code:

for (int i = 2; i <= 20; i += 2)
{
    Console.WriteLine(i);
}

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading