Back

import java.util.*;
public class example4 {

   public static void main(String[] args)
   {
      int c;  //Counter variable
      int n;  //starting number
      int sum; //Variable used for storing accumulation

      //INPUT
      System.out.println("Example 4");
      System.out.println("Enter n:");
      n = readInt();

      //PROCESSING AND CALCULATIONS
      sum = 0;
      for (c=1; c<=n; c++)
      {
         //Accumulate the totals into the variable sum
         //Could also write sum += c (Take the last total of sum and add c)
         sum = sum + c;
      }

      //OUTPUT
      System.out.println("Sum of 1 + 2 + .. + n = " + sum);
   }

   public static int readInt()
   {
      Scanner sc = new Scanner(System.in);
      int x = sc.nextInt();
      return x;
   }
}

Top