Problem 5-1

CSharp · Console

/Program.cs

// Write a program that inputs positive integer n and prints squares from 1 to n*n
// The program can use only + and – operations on integers and total number of such
// operations should be proportional to n.
using System;
					
public class Program
{
	public static void Main()
	{
		Console.Write("Enter the value of n: ");
        int n = Convert.ToInt32(Console.ReadLine());
		
		int k = 0;
		int k2 = 0;
		// invariant: all squares from 1 to k are printed
		//            and k2 = k*k and k <=n
		while (k != n)
		{
			// k < n
			k++;
			// k2 = (k-1)(k-1) = k*k - 2k - 1 and k<=n
			k2 = k2 + k + k - 1;
			// k2 = k*k
			// all squares from 1 to k-1 are printed and k<=n
			Console.WriteLine("Square of {0} is {1}", k, k2);
			// all squares from 1 to k are printed and k<=n
		}
		// invariant: all squares from 1 to n are printed

		// Time = O(n)
	}
}
;