Sum a Range of Numbers


 
   //======================================================
   // wyatt
   //    accepts 2 ints
   //    loops from start to end
   //       calculates the sum
   //    return a decimal sum          
   // example:
   //   1 to 500 million
   //   sum is 125,000,000,250,000,000 - 125 quadrillion
   //======================================================
   private  static decimal SumRange(int start, int end)
   {
      // use decimal to hold LARGE sums
      decimal sum = 0;
      
      try // protect
      {
         // loop from start to end accumulating the sum
         for(int i=start; i<=end; i++)
         {
            checked // throws an exception upon overflow
            {
              sum += (decimal)i;
            }
         }
      }
      
      // error - display message, but don't abort
      catch (Exception ex)
      {
          MessageBox.Show(ex.Message);
          return -1; // err return
      }
            
      // give back the calculated sum
      return sum;
   }     
      
TO CALL:
  
                  
      int x = 5, y = 9;
      int answer = SumRange( x, y ); // returns 35 in the variable, answer
                                     // because 5+6+7+8+9 equals 35
                                     
      if (answer != -1)
      {
         ...