// Prints calculated sum of numbers from 1 to n. private static void PrintCalculate() { Console.WriteLine("Calculate the sum of numbers from 1 to n!"); // Need to define default n for use that in while loop. int n = 0; // while-loop for a valid positive number input. while (n <= 0) { Console.Write("\nEnter a valid positive number: "); try { // An exception throws if input will be non number(character etc.) n = int.Parse(Console.ReadLine()); } catch (FormatException e) { Console.WriteLine("Error: " + e.Message); } // Note: Overflow does not need to be taken into account. } // Prints calculated sums by results of methods. Console.WriteLine("\nImplementation using a for-loop: " + SumOfNumbers.Sum_A(n)); Console.WriteLine("Implementation using a while-loop: " + SumOfNumbers.Sum_B(n)); Console.WriteLine("Implementation using LINQ: " + SumOfNumbers.Sum_C(n)); Console.WriteLine("Implementation that runs in constant time O(1): " + SumOfNumbers.Sum_D(n)); }
public static void PrintInAscendingOrder() { SumOfNumbers.Sum_A(5); Console.WriteLine("Numbers from 1 to 100, in ascending order:"); for (int i = 1; i <= 100; i++) { Console.Write(i + "\t"); //beautifying } }