Wednesday, 15 July 2015

Java Programs Made Easy

Q)... Retrieve the odd numbers till given input number. add and subtract it consecutively and return the result.
Input:9
Output:1+3-5+7-9=-3



  1. package Set1;
  2. import java.util.*;
  3. public class ClassSet7 {
  4.  public static int consecutiveSumSubofOddNos(int n){
  5.   List<Integer> l1=new ArrayList<Integer>();
  6.   for(int i=1;i<=n;i++)
  7.    if(i%2!=0)
  8.     l1.add(i);
  9.   int n1=l1.get(0);
  10.   for(int i=1;i<l1.size();i++)
  11.    if(i%2!=0)
  12.     n1=n1+l1.get(i);
  13.    else
  14.     n1=n1-l1.get(i);
  15.   return n1;
  16.  }
  17.  public static void main(String[] args) {
  18.   Scanner s=new Scanner(System.in);
  19.   int n=s.nextInt();
  20.   System.out.println(consecutiveSumSubofOddNos(n));
  21.  }
  22. }