Skip to content

Commit b806766

Browse files
committed
feat: Add SumElementsVarargs to calculate sum of integers using varargs
WHAT the code does: Defines a SumElementsVarargs class with a sum(int... A) method: - Accepts a variable number of integer arguments (varargs). - Iterates through them, accumulating a total sum. - Returns the computed result. main() demonstrates usage by summing 1, 2, 3, 4, 5 → result = 15. WHY this matters: Showcases Java varargs, which simplify APIs by allowing flexible numbers of arguments without overloading. Demonstrates iteration over varargs using a traditional for loop. Encapsulates reusable logic in a method that adapts to different input sizes. Provides a concise alternative to array-based summation. HOW it works: When obj.sum(1, 2, 3, 4, 5) is called: - Java internally creates an int[] array {1, 2, 3, 4, 5}. - The method iterates from index 0 to A.length-1, adding elements to total. - Returns 15, which is printed in main(). Tips and gotchas: Varargs are syntactic sugar for arrays; at runtime, an array is always created. Be cautious when mixing varargs with other parameters—varargs must come last in the method signature. If no arguments are passed, A.length == 0 and total will remain 0. For performance-sensitive cases with frequent calls, repeated array creation may be costly. Use-cases: Utility function for summing numbers without requiring manual array creation. Educational demonstration of varargs in Java. Foundation for building statistical helpers (average, min, max) using varargs. Simplifies method calls in APIs that handle flexible input sizes. Short key: class-sumelementsvarargs varargs integer-sum. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent a2a4de5 commit b806766

File tree

1 file changed

+6
-12
lines changed

1 file changed

+6
-12
lines changed
Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,17 @@
1-
public class SumElementsVarargs
2-
{
1+
public class SumElementsVarargs {
32
// Method to sum elements using varargs
4-
int sum(int... A)
3+
int sum(int... A) {
4+
int total = 0; // Initialize total sum.
55

6-
{
7-
int total = 0; // Initialize total sum
8-
for (int i = 0; i < A.length; i++)
9-
{
6+
for (int i = 0; i < A.length; i++) {
107
total += A[i]; // Add each element to total
118
}
129
return total; // Return the total sum
1310
}
14-
15-
public static void main(String[] args)
16-
{
11+
public static void main(String[] args) {
1712
SumElementsVarargs obj = new SumElementsVarargs();
1813

19-
// Example usage
2014
int result = obj.sum(1, 2, 3, 4, 5); // Passing multiple integers
2115
System.out.println("Sum: " + result); // Should print "Sum: 15"
2216
}
23-
}
17+
}

0 commit comments

Comments
 (0)