Problem 2-2

CSharp · Console

/Program.cs

// The factorial function “n!” is defined as: 0! = 1, n! = (n-1)! x n.
// Write a program that inputs nonnegative n and prints n!
using System;
using System.Diagnostics;
					
public class Program
{
	public static int InputInt(string prompt)
	{
		Console.Write("Enter " + prompt + ":");
		return Convert.ToInt32(Console.ReadLine());
	}
	
    public static void Main(string[] args)
    {
       	int n = InputInt("n");
       	Trace.Assert(n >= 0);
		
		int r = 1;
		int i = 0;
		// invariant: r = i! and 1<=i<=n
		while (i != n)
		{
			// r = i! and i<n
			i = i + 1;
			// r = (i - 1)! and i<=n
			r = r * i;
			// r = (i - 1) * i = i! and i<=n
		}
		// r = i! and i<=n  => r = n!
		Console.WriteLine("{0}! = {1}", n, r);
    }
}
;