settingsAccountsettings
Menusettings

Q: Can you give me examples of nested for loops in C#?

+5 votes

Can you please give me some examples of nested for loops? I need to realize how to use for loops properly and the nested options as well! thanks

asked in C# category by user eiorgert

3 Answers

+1 vote

Here is one example called "Half triangle of numbers":

using System;

class TriagnelNumbers
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        for (int row = 1; row <= n; row++)
        {
            for (int column = 1; column <= row; column++)
            {
                Console.Write("{0} ", column);
            }
            Console.WriteLine();
        }
    }
}

 


half triangle of numbers in C#

 

answered by user mitko
edited by user golearnweb
+1 vote

Another example (checking for prime numbers in given numerical range):

using System;

class CheckPrimeNumbers
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        int m = int.Parse(Console.ReadLine());
        for (int number = n; number <= m; number++)
        {
            bool prime = true;
            int divider = 2;
            int maxDivider = (int)Math.Sqrt(number);
            while (divider <= maxDivider)
            {
                if (number % divider == 0)
                {
                    prime = false;
                    break;
                }
                divider++;
            }
            if (prime)
                Console.Write("{0} ", number);
        }
    }
}
answered by user nikole
edited by user golearnweb
+1 vote

Nested for loops used to print Happy numbers:

using System;

class TriagnelNumbers
{
    static void Main()
    {
        {
            for (int a = 1; a <= 9; a++)
                for (int b = 0; b <= 9; b++)
                    for (int c = 0; c <= 9; c++)
                        for (int d = 0; d <= 9; d++)
                            if (a + b == c + d)
                                Console.WriteLine("{0}{1}{2}{3}", a, b, c, d);
        }

    }
}
answered by user richard8502
edited by user golearnweb
...