Core C#

For Loop Examples

This code example contains three example for loops: The first prints powers of 2. The second initializes and updates two variables. The third uses nested for loops to print out a multiplication table.

Program.cs

using System;

namespace XoaX {
    class Program {
        static void Main(string[] args) {
            // 1. Count powers of 2 from 2 to 256
            Console.Write("1. ");
            for (int i = 2; i < 500; i *= 2) {
                Console.Write(i + "  ");
            }
            Console.WriteLine();

            // 2. A for loop with a mulitple initializations and updates
            Console.Write("2. ");
            for (int j = 2, k = 0; j * k < 25; ++j, k += 2) {
                Console.Write("j = " + j + ", k = " + k + " | ");
            }
            Console.WriteLine();

            // 3. Nested for loop that print a muliplication table
            Console.WriteLine("3. Multiplication Table");
            for (int i = 1; i < 10; ++i) {
                for (int j = 1; j < 10; ++j) {
                    // Add a space for values less than 10
                    if (i * j < 10) {
                        Console.Write(" ");
                    }
                    Console.Write(i * j + "  ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
    }
}
 

Output

1. 2  4  8  16  32  64  128  256
2. j = 2, k = 0 | j = 3, k = 2 | j = 4, k = 4 |
3. Multiplication Table
 1   2   3   4   5   6   7   8   9
 2   4   6   8  10  12  14  16  18
 3   6   9  12  15  18  21  24  27
 4   8  12  16  20  24  28  32  36
 5  10  15  20  25  30  35  40  45
 6  12  18  24  30  36  42  48  54
 7  14  21  28  35  42  49  56  63
 8  16  24  32  40  48  56  64  72
 9  18  27  36  45  54  63  72  81

Press any key to continue . . .
 
 

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