CSharp - Write program to handle with int type Overflow

Requirements

You will use long type to store the result of int calculation.

Hint

Convert the million into a long type before the calculation starts.

  • Assigning the million to a variable of type long
  • Using an explicit type cast with (long)million

Demo

using System;
class Program{//w  w w .j a va  2s . co  m
    static void Main(string[] args){
        int million = 1000000;

        long millionInLong = million;
        long correctResult = millionInLong * millionInLong;
        Console.WriteLine("Million times million: " + correctResult.ToString("N0"));

        // Alternative calculation of a big valule 
        long r = (long)million * (long)million;
        Console.WriteLine("Million times million: " + r.ToString("N0"));
    }
}

Result