-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVarargs.java
More file actions
34 lines (26 loc) · 809 Bytes
/
Copy pathVarargs.java
File metadata and controls
34 lines (26 loc) · 809 Bytes
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
/*
Problem:
Create a class Add with a method add() that accepts
a variable number of integers and prints their sum
in the required format.
*/
class Add {
// Method using Varargs to accept multiple integers
public void add(int... numbers) {
// Variable to store the sum
int sum = 0;
// Traverse all numbers
for (int i = 0; i < numbers.length; i++) {
// Add current number to sum
sum += numbers[i];
// Print current number
System.out.print(numbers[i]);
// Print '+' after each number except the last one
if (i < numbers.length - 1) {
System.out.print("+");
}
}
// Print '=' followed by the total sum
System.out.println("=" + sum);
}
}