OneBite.Dev - Coding blog in a bite size

Use A Basic Loop In C#

Code snippet for how to Use A Basic Loop In C# with sample and detail explanation

C# is an object-oriented programming language widely used for development of enterprise-level applications. Understanding core concepts such as loops is crucial to becoming an efficient C# developer.

Code snippet for Basic Loop in C#

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

Code Explanation for Basic Loop in C#

In the above code snippet, we demonstrate the use of a basic ‘for’ loop in C#.

The ‘for’ loop starts with the keyword ‘for’ and followed by the conditions enclosed in parentheses. In our case, we have three parts:

  1. int i = 0: This is the initialization. We declare an integer variable i and set it to 0.

  2. i < 10: This is the condition that the loop will check before each iteration. In the code snippet, it checks if the variable ‘i’ is less than 10.

  3. i++: This is the update statement which runs after each iteration of the loop. The ‘i++’ operation increments the value of ‘i’ by 1 each time the loop runs.

Within the curly braces {} following the conditions, we have the loop’s body, which executes on each iteration of the loop when the condition is met. In the displayed example, Console.WriteLine(i); is the body of the loop which will print the current value of ‘i’ with each iteration.

In essence, the loop will print out the integers from 0 to 9 in the console. Once ‘i’ reaches 10, the condition i < 10 fails, and the loop terminates.

Learning to use basic loops is essential in mastering C# or any other programming language. They allow us to perform repetitive tasks efficiently, making our code cleaner and easier to understand.

c-sharp