C# Looping


Here is some sample code on how to write loops in C#.

class Program  // Looping
{
    static void Main(string[] args) {
        // All loops output 1 to 10 in a column in console.
        int i = 1;
        do  { 
            WriteLine("{0}", i++);
            // The suffix version of the ++ operator will
            // increment i after it is written to the screen
            // but before it hits the while <test>
        } while (i <= 10);
        //
        i = 1;
        while (i <= 10)
        {
            WriteLine($"{i++}");
        }
        // You could declare your counter outside of the for loop
        // so that it is accessible after the for loop finishes,
        // otherwise it will not be accessible: 
        // int myi = 1; for ( myi = 1; myi <= 10; ++myi)
        for (int myi = 1; myi <= 10; ++myi)
        {
            WriteLine($"{myi}");
        }  
        ReadKey();
    }
    // break; ends loop  immediately
    // continue; current loop cycle ends immediately and
    // execution continues with the next loop cycle
    // return; jump out of loop and end its calling function
}



Leave a comment

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