How To Sum The Even Numbers Using Loop

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

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 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);

Tags:

Java