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.

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

Advertisements

 

We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.

Share on Google+Share on Google+

A program to find the sum of odd number

Posted on: June 20, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: A program to find the sum of odd number  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads