-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumUpToN.java
More file actions
37 lines (34 loc) · 1.23 KB
/
SumUpToN.java
File metadata and controls
37 lines (34 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.Scanner;
public class SumUpToN {
// Recursive method to calculate the sum of integers up to n
public static int sumUpToN(int n) {
// Base case: if n is 0, return 0
if (n == 0) {
return 0;
}
// Recursive case: add n to the sum of integers up to n-1
return n + sumUpToN(n - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer up to which you want to add: ");
try {
int userInput = scanner.nextInt();
if (userInput < 0) {
System.out.println("Please enter a positive integer.");
} else {
if (userInput > 100) {
System.out.println("Please enter an integer up to 100.");
return;
} else {
int result = sumUpToN(userInput);
System.out.println("The sum of integers up to " + userInput + " is: " + result);
}
}
} catch (Exception e) {
System.out.println("Sorry, this is not a good input, try again.");
} finally {
scanner.close();
}
}
}