You are given two inputs:
int num1; int num2; |
You can assume that the following:
- num2 > num1 ==> TRUE
You are to write a program that will calculate and print out the SUM OF ODD numbers in between num1 and num2 inclusive. Your output should all be on one line, separated by spaces. Sample input/output:
#1: 3 #2: 11 Output: 35
#1: 4 #2: 20 Output: 96
#1: -2 #2: 6 Output: 8 |
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
//start on line 11
int cnt=num1;
int sum=0;
if(num1%2==0) {cnt+=1;}
while(cnt<=num2) {
sum+=cnt;
cnt+=2;
}
System.out.println(sum);
}
}
|
반응형
'Java_beginner(Repl.it) > Auto-Graded-Course(AP CS A)' 카테고리의 다른 글
038 - Method Header Practice 3 (0) | 2019.12.10 |
---|---|
036 - Method Header Practice 1,2 (0) | 2019.12.10 |
034 - Big Number Program (From Decoding) (0) | 2019.12.10 |
033 - For Loop Challenge 2 (optional) (0) | 2019.12.07 |
032 - For Loop Challenge 1 (optional) (0) | 2019.12.07 |