C# Keywords Tutorial Part 35: for

C# Keywords Tutorial Part 35: for

C# is a powerful and versatile programming language that offers a variety of features to developers. One such feature is the “for” keyword, which is used to create loops. In this blog post, we will explore the “for” keyword in C# and how it can be used to create different types of loops.

The “for” keyword is a control statement that is used to create loops. The syntax for the “for” keyword is as follows:

for(initialization; condition; iteration)
{
    // statements
}

The “for” loop consists of three parts: the initialization, the condition, and the iteration. The initialization is executed only once, at the beginning of the loop. The condition is evaluated at the beginning of each iteration, and if it is true, the loop continues. The iteration is executed at the end of each iteration, just before the condition is evaluated again.

Now, let’s take a look at some examples of how the “for” keyword can be used in C#.

Example 1: Counting from 1 to 10

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

In this example, we are initializing the loop variable “i” to 1, and setting the condition to continue as long as “i” is less than or equal to 10. At the end of each iteration, we are incrementing “i” by 1. This loop will print the numbers from 1 to 10 to the console.

Example 2: Summing the values of an array

int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;

for(int i = 0; i < numbers.Length; i++)
{
    sum += numbers[i];
}

Console.WriteLine(sum);

In this example, we are initializing the loop variable “i” to 0, and setting the condition to continue as long as “i” is less than the length of the “numbers” array. At the end of each iteration, we are adding the value of the current element in the array to the “sum” variable. This loop will calculate the sum of the values in the “numbers” array and print it to the console.

Example 3: Looping through a string

string text = "Hello, world!";

for(int i = 0; i < text.Length; i++)
{
    Console.WriteLine(text[i]);
}

In this example, we are initializing the loop variable “i” to 0, and setting the condition to continue as long as “i” is less than the length of the “text” string. At the end of each iteration, we are printing the character at the current index of the “text” string to the console. This loop will print each character in the “text” string to the console.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *