I need help on this code I seem to have a problem regarding on summing the even numbers, what I want to happen is that the even numbers will be outputted and at the same time there will be an output where all the even numbers are summed within the inputted range of the user. I am just a beginner at coding and I hope some people can help me.
import java.util.*;
public class Loop
{
//Start
public static void main(String args[])
{
Scanner console = new Scanner(System.in) ;
System.out.println("Enter Start Number") ;
int start =console.nextInt();
System.out.println("Enter End Number") ;
int end =console.nextInt();
int sum = 0;
System.out.println("The even numbers between "+start+" and "+end+" are the following: ");
for (int r = start; r <= end; r++)
{
//if number%2 == 0 it means its an even number
if(r % 2 == 0)
{
System.out.println(r);
}
}
}
}
The sum of even numbers formula is obtained by using the sum of terms in an arithmetic progression formula. The formula is: Sum of Even Numbers Formula = n(n+1) where n is the number of terms in the series.
Python program to calculate sum of even numbers using for loop. In the given program, we first take user input to enter the maximum limit value. Then, we have used the for loop to calculate the sum of even numbers from 1 to that user-entered value.
A concise way using Java streams. Just putting it here so that you know that there is another way to do this:
int sum = IntStream.range(start, 1 + end).filter(num -> 0 == num % 2).peek(System.out::println).sum();
System.out.println(sum);
You can use with sum+=r;
and get the sum :
public static void main(String args[])
{
Scanner console = new Scanner(System.in) ;
System.out.println("Enter Start Number") ;
int start =console.nextInt();
System.out.println("Enter End Number") ;
int end =console.nextInt();
int sum = 0;
System.out.println("The even numbers between "+start+" and "+end+" are the following: ");
for (int r = start; r <= end; r++)
{
//if number%2 == 0 it means its an even number
if(r % 2 == 0)
{
sum += r;
System.out.println(r);
}
}
System.out.println("The sum of even numbers between :"+start +" - "+end +" is : "+sum);
}
}
Output :
Enter Start Number
10
Enter End Number
20
The even numbers between 10 and 20 are the following:
10
12
14
16
18
20
The sum of even numbers between :10 - 20 is : 90
you are almost there
int sum = 0;
System.out.println("The even numbers between "+start+" and "+end+" are the following: ");
for (int r = start; r <= end; r++)
{
if(r % 2 == 0)
{
sum = sum + r;
System.out.println(r);
}
}
System.out.println("the sum : "+sum);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With