OneBite.Dev - Coding blog in a bite size

Do A For Loop In C#

Code snippet for how to Do A For Loop In C# with sample and detail explanation

Understanding the basics of programming is an essential skill for every developer. One such basic concept that bears immense importance in any programming language, including C#, is a ‘for’ loop. Here, we’ll guide you through a simple tutorial on how to conduct a ‘for’ loop in C#.

Code snippet: ‘For’ Loop in C#

In this section, we are providing a simple example of a ‘for’ loop in C#.

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

Code Explanation for ‘For’ Loop in C#

The “for” loop in the snippet gives the command to print numbers from 0 to 4 on the console. Here’s how it works step-by-step.

  • int i = 0: This is the initialization operation. It’s where you declare your variable (in this case, ‘i’) and set it to 0. This is essentially your starting point for the loop.

  • i < 5: In this condition statement, the program checks if ‘i’ is less than 5. As long as ‘i’ is less than 5, the loop will continue. Once ‘i’ reaches 5 (or a number above), the loop will stop execution.

  • i++: This is the iteration operation. After every loop, ‘i’ will increase by 1. The ’++’ is shorthand for saying ‘add 1 to the current value’.

  • Console.WriteLine(i): This is your loop body. This piece of code gets executed for each iteration of the loop. In this case, it prints the current value of ‘i’ to the console.

The loop runs as follows: At the start, ‘i’ is equal to 0. Then it checks the condition—since 0 is less than 5, it moves on and prints ‘0’ on the console. After printing, it scales ‘i’ upwards by 1. Now ‘i’ equals 1. Again, it checks the condition—1 is still less than 5. So, it prints ‘1’. This process goes on till ‘i’ equals 4. Once ‘i’ equals 5, it won’t print because 5 is not less than 5. Hence the ‘for’ loop ends after printing from 0 to 4.

The knowledge of how to carry out a ‘for’ loop in C# is a valuable addition to your programming skills. Practice this code until you’re familiar with it as these loops will come in handy when you need to run a block of code a certain number of times. Now you’re ready to start looping!

c-sharp