Core C#

For Loops

A for loop can be used to loop while a condition holds. It can also initialize conditions before it starts its loop and perform an update action at the end of each loop. Below, we have a program that demonstrates a simple for loop that counts from 0 to 9. The first part of the for statement, before the first semicolon, is the initialization and is executed before the loop starts. In this case, the initialization declares the variable i and sets its value to 0. The second part of the for loop, between the semicolons, is the conditional portion that controls whether the looping continues. In this case, the conditional statement checks to make sure that the value of i is less than 10. The third part of for loop, after the second semicolon, is the update, which increments the value of i. The update is executed once at the end of the loop and, just before the conditional checks whether it should loop again.

Program.cs

using System;

namespace XoaX {
    class Program {
        static void Main(string[] args) {
            // Count from 0 to 9
            for (int i = 0; i < 10; ++i) {
                Console.Write(i + "  ");
            }
            Console.WriteLine();
        }
    }
}
 

Output

0  1  2  3  4  5  6  7  8  9
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.