Thursday 15 June 2017

How to print sum of even numbers in java

Program:

package JavaCoders;
import java.util.Scanner;
/**
*
* @author Bsb
*/
class even_sum
{
public static void main(String[] args)
{
int i;
int sum=0;
System.out.println("Enter the number upto you want to sum:");
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
for(i=1;i<=num;i++)


{
if(i%2!=0)
{
continue;
}
sum=sum+i;
}
System.out.println("The sum of Even number upto"+" "+num+" is: "+sum);
}
}



In this program ,it is generating sum of even numbers by applying input .One thing to remember is that you must have to import package name java.util.Scanner. Using this it will ask the user to supply input Like in above program it is asking “Enter the number upto you want to sum”. After supplying input the loop will run upto the number you just supplied.The logic behind the code is that the even number can be found ,if the number after dividing by 2 generates zero than it is an even number otherwise it is not or if the number after dividing by 2 doesn’t generate zero then loop will be continued otherwise it is add to the variable initialize to zero. After that when loop reaches to it’s end all the even numbers are added that can be displayed using print statement.

OUTPUT:

How-to-print-sum-of-even-numbers-in-java

No comments:

Post a Comment

Oracle / PLSQL: FOR LOOP

set serveroutput on; declare a1 varchar2(100); begin select count(*) into a1 from employees; for i in 1..a1 loop dbms_output.put_line...