From 27601bd3f6ea9e7a42b9ed373da21459126198fe Mon Sep 17 00:00:00 2001 From: "jason.zhu" Date: Mon, 15 Feb 2021 04:30:09 +0000 Subject: [PATCH] Finished first C# code --- Factorial/Factorial.cs | 60 ++++++++++++++++++++++++++++++++++++++++++ Factorial/compile.txt | 3 +++ 2 files changed, 63 insertions(+) create mode 100644 Factorial/Factorial.cs create mode 100644 Factorial/compile.txt diff --git a/Factorial/Factorial.cs b/Factorial/Factorial.cs new file mode 100644 index 0000000..92d5c48 --- /dev/null +++ b/Factorial/Factorial.cs @@ -0,0 +1,60 @@ +using System; + +public class Functions +{ + public static long Factorial(int n) + { + // Test for invalid input. + if ((n < 0) || (n > 20)) + { + return -1; + } + + // Calculate the factorial iteratively rather than recursively. + long tempResult = 1; + for (int i = 1; i <= n; i++) + { + tempResult *= i; + } + return tempResult; + } +} + +class MainClass +{ + static int Main(string[] args) + { + // Test if input arguments were supplied. + if (args.Length == 0) + { + Console.WriteLine("Please enter a numeric argument."); + Console.WriteLine("Usage: Factorial "); + return 1; + } + + // Try to convert the input arguments to numbers. This will throw + // an exception if the argument is not a number. + // num = int.Parse(args[0]); + int num; + bool test = int.TryParse(args[0], out num); + if (!test) + { + Console.WriteLine("Please enter a numeric argument."); + Console.WriteLine("Usage: Factorial "); + return 1; + } + + // Calculate factorial. + long result = Functions.Factorial(num); + + // Print result. + if (result == -1) + Console.WriteLine("Input must be >= 0 and <= 20."); + else + Console.WriteLine($"The Factorial of {num} is {result}."); + + return 0; + } +} +// If 3 is entered on command line, the +// output reads: The factorial of 3 is 6. \ No newline at end of file diff --git a/Factorial/compile.txt b/Factorial/compile.txt new file mode 100644 index 0000000..5cbbd1e --- /dev/null +++ b/Factorial/compile.txt @@ -0,0 +1,3 @@ +To compile Factorial.cs. + +In Windows, open Developer PowerShell for VS 2019, and enter command `csc Factorial.cs` \ No newline at end of file