Find sum of all even numbers between 1 to n
Sample Output
Find sum of all even numbers between 1 to n. Enter a number: 10 2 4 6 8 10 Sum: 30
Java-Source Code
//package loopinjava;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n, number, sum = 0;
Scanner input = new Scanner(System.in);
System.out.println("Find sum of all even numbers between 1 to n.\n");
System.out.print("Enter a number: ");
number = input.nextInt();
for (n = 1; n <= number; n++) {
if (n % 2 == 0) {
sum += n; // Or, sum = sum + n;
System.out.println(n);
}
}
System.out.println("Sum: " + sum);
}
}
Sample Output
Find sum of all even numbers between 1 to n. Enter a number: 12 2 4 6 8 10 12 Sum: 42
No comments:
Post a Comment