title: How to Subtract n numbers using for loop in java?
body: <p>When I use for loop for subtraction, i don't get a correct output. </p>
  
  <p>What logic should i apply in my code to get my subtraction correctly using for loop?</p>
  
  <p>Please help me as i am new in JAVA.</p>
  
  <p>My code is as Follow:</p>
  
  <pre><code>import java.io.*;
  import java.util.*;
  
  class Sub
  {
      public static void main(String args[])
      {
          Scanner s=new Scanner(System.in);
          int a,n,i;
          String yn;
          boolean loop=true;
  
          while(loop)
          {
              try
              {
                  do
                  {
                      loop=true;
                      System.out.println("Enter how many numbers to Subtract?: ");
                      n=s.nextInt();
                      int sum=0;
                      for(i=1;i&lt;=n;)
                      {
                          try
                          {
                              System.out.println("Enter number "+i+" : ");
                              a=s.nextInt();
                              sum=a-sum;
                              i++;
                          }
                          catch(Exception e)
                          {
                              System.out.println("Invalid Entry. Try again!!");
                          }
                      }
                      System.out.println("Answer is:"+sum);
                      System.out.println("Do you want to continue?(Y/N): ");
                      yn=s.next();
                      loop=yn.equals("Y")||yn.equals("y");
                  }while(loop);
              }
              catch(Exception e)
              {
                  System.out.println("Re-enter the Limit");
              }
          }
  
      }
  }
  </code></pre>