Write a program that will accept a number n and display the sum of all even numbers and
the sum of all odd numbers from 1 to n and the number of rows.
import java.util.Scanner;
public class App {
/**
* The start point of the program
*
* @param args
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter n: ");
int n = keyBoard.nextInt();
int sumEvenNumbers = 0;
int sumOddNumbers = 0;
int evenRows=0;
int oddRows=0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sumEvenNumbers += i;
evenRows++;
}
if (i % 2 != 0) {
sumOddNumbers += i;
oddRows++;
}
}
System.out.println("\nSum of even numbers = " + sumEvenNumbers);
System.out.println("Sum of odd numbers = " + sumOddNumbers);
System.out.println("The number of even rows = " + evenRows);
System.out.println("The number of odd rows = " + oddRows);
keyBoard.close();
}
}
Comments
Leave a comment