2
07/11/2024 2:03 pm
Argomento iniziale
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
3 risposte
1
07/11/2024 2:04 pm
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(); } } }
1
07/11/2024 2:05 pm
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); } } }
1
07/11/2024 2:05 pm
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); } } }