Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Beginners A program to find the sum of odd number

 
 

Share on Google+Share on Google+

A program to find the sum of odd number

Advertisement
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

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 20, 2013

Related Tutorials

Discuss: A program to find the sum of odd number  

Post your Comment


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