JAVA PROGRAM TO CALCULATE THE SUM OF ODD NUMBERS

 

Numbers  that  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(which  are  ending  with  1,3,5,7,9)

 

 

Example:

 

Input: 5

Output:

 

 

Sum  of   Odd  Numbers present  from number  1  to  5 =1+3+5=9

Sum  of  Even  Numbers  present  from  number  1  to  5=2+4=6

 

 

 

 

 

class    SumofOddNumbers {

    public  static  void  main(String  args[] ) {

     int  n,oddSum=0;

     Scanner  sc=new  Scanner(System.in);

     System.out.println(“Enter   the  number”);

     n=sc.nextInt();

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

         if(i%2!=0){

            oddSum=oddSum+i;

     }

  }

 

  System.out.println(“Sum  of  odd  numbers  upto” +n+“=”+oddSum); 

 

  }

}

 

 

 

 

Leave a Comment

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