Java Program to Find the Sum of First N Odd & Even Numbers

 

Numbers  which  are  divisible  by  2  are  called  even  numbers (ending  with  0 ,2,4,6,8 ),  while  numbers  that  are  not  divisible  by  2  are  called  odd  numbers (ending  with 1, 3,5,7,9 )

 

 

 Example : 9

 

 Output :

 

Sum  of  First  9  Even  Numbers = 2+4+6+8+10+12+14+16+18=90

 Sum  of  First  9  Odd  Numbers = 81

 

 

Approach :  Iterative  Method

 

 

 

class   Sum{

     public  static  void  main(String  args[] ) {

     int  n=9;

      int  evenSum=0,oddSum=0;

   for(int  i=1;i<=2*n;i++ ) {

       if(i%2==0){

         evenSum=evenSum+i;

   }

     else{

        oddSum=oddSum+i;

  }

        }

     System.out.println(“Sum  of  First “ +n +“Even Numbers=”+evenSum);

 

      System.out.println(“Sum of  First”+n+“Odd Numbers= “ +oddSum);

     }

  }

 

 

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *