Showing posts with label How to pas unlimited parameter to function in Java. Show all posts
Showing posts with label How to pas unlimited parameter to function in Java. Show all posts

Thursday, 25 December 2014

Increase number of arguments without changing the parameters of function in Java

Structure of the Problem Requirements 

In this problem we will learn how to change or increase the number of parameters of a function without changing the its prototype or parameters in Java. The logic behind this code is very interesting. Each time when you pass the numbers in function's parameters the function will calculate them. Here is the complete source code of this problem which help you in better understanding.

Source Code


public class MyMain {

public static void main(String[] args) {
System.out.print(sumAll(1,2)+"\n");
System.out.print(sumAll(1,2,3)+"\n");
System.out.print(sumAll(1,2,3,4)+"\n");
System.out.print(sumAll(1,2,3,4,5)+"\n");
}
// which takes any number of integers and returns their sum
public static int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i<numbers.length;i++)
{
result+=numbers[i];
return result;
}
}


Output of the Program

Parameters Logic program in Java
Parameters Logic program in Java