Valentino
Valentino

Reputation: 21

Usind for and while loops better

Trying to design an application which reads an integer and prints the sum of all even integers between 2 and the input value. Can anybody help me with the last bit?!

import java.util.Scanner;

public class IntegerValue {

    // main method
    public static void main(String[] args) {

        // Data fields
        int a;
        // end

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter an integer greater than 1");
        a = sc.nextInt();
        if (a <= 1) {
            System.out.println("Input Value must not be less than 2");
        }
        while (a > 1) {
            int sum = 0;
            if (a % 2 == 0) {
                sum += a;
                a = a - 1;
            }
            System.out.println(sum);
        }

    }
}

Upvotes: 0

Views: 142

Answers (2)

Juned Ahsan
Juned Ahsan

Reputation: 68715

You need to define your sum variable out of while loop, otherwise it will get re-initialized with every iteration of loop. Also sum should be printed outside the while loop if you just want the final sum. Here is code update, you may try:

 int sum = 0;
 while (a > 1) {
            if (a % 2 == 0) {
                sum += a;
                a = a - 1;
            }
        }
 System.out.println(sum);

Upvotes: 1

user2672373
user2672373

Reputation:

The most significant part, sum being initialized have already been pointed out; but it seems that they missed out the printing part; it would be better to print sum after the loop has been executed. So this is how the last section of your program should preferably look like:

int sum = 0;
while (a > 1) {
    if (a % 2 == 0) {
        sum += a;
        a = a - 1;
    }
}
System.out.println(sum);

Upvotes: 2

Related Questions