A program to find the sum of odd number

Ads
 

A program to find the sum of odd number

This tutorial will help you to find the sum of odd numbers up to a limit number in java.

This tutorial will help you to find the sum of odd numbers up to a limit number in java.

A program to find the sum of odd number

In this section you will learn how to find the sum of odd number in the series up to the given number in java. The java.io package  provide class scanner which read the input from the console. Now here is the simple example which will help you to find the sum of odd number.

 import java.util.Scanner;
 public class Sum {

 public static void main(String args[])
 {
  System.out.println("Enter the limit number");
  Scanner sin;
  int m,n,sum=0;
  sin=new Scanner(System.in);
  n=sin.nextInt(); 
  for(int i=1;i<n;i++)
  { 
   if(i%2!=0)
   sum=sum+i; 
  }
   System.out.println("Sum of odd number = "+sum);
   }
}

In the above program, Creating a class sum and with the help of scanner class getting input from the user, applying a loop which will keep on executing up to the number provided by user. Within the loop checking for odd number in the if statement (i%2!=0), then adding to the sum variable and outside loop sum value will be displayed to the console.

Output : After compiling and executing the above program

Download  SourceCode

Ads

Ads