Skip to Content
CoursesCSC122หาผลรวมของเลขคี่หรือเลขคู่ 20 จำนวนถัดไปจากค่าเริ่มต้น

หาผลรวมของเลขคี่หรือเลขคู่ 20 จำนวนถัดไปจากค่าเริ่มต้น

โจทย์

Write a program to add the next 20 numbers from the given seed number according to the following conditions:

  1. If the seed number is odd, add odd numbers including the seed as well.

  2. If the seed number is even, add even numbers including the seed as well.

The input is the seed number. The output is the result of the adding.

For example if 55 is a seed number. Then the result is:

55 + 57 + 59 + 61 + 63 + 65 + 67 + 69 + 71 + 73 + 75 = 715
InputOutput
55715
46616

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int start = scanner.nextInt(); int end = start + 20; int sum = 0; for (int i = start; i <= end; i+=2) { sum += i; } System.out.println(sum); } }

คำอธิบาย

ปรับปรุงล่าสุด