Java Varargs and Recursion Examples

Day 16: VarArgs and Recursion 🔸Variable Arguments (Varargs): A function with varargs can be created in Java using the following syntax: public static void foo(int... arr) { // arr is available here as int[] arr } foo can be called with zero or more arguments, like this: foo(7) foo(7, 8, 9) foo(1, 2, 7, 8, 9) We can also create a function bar like this: public static void bar(int a, int... arr) { // code } bar(1) bar(1, 2) bar(1, 7, 9, 11) 🔸Example static int avg(int... arr) { int result = 0; int avg = 0; for (int element : arr) { result += element; } avg = result / arr.length; return avg; } public static void main(String[] args) { System.out.println("The average is " + avg(3, 5, 8, 7)); } 🔸Recursion A function in Java can call itself. Such calling of a function by itself is called recursion. 🔸Syntax of Recursion in Java: returnType functionName(parameters) { if(base_condition) { return value; } else { return functionName(smaller_problem); } } 🔸Example: Factorial Using Recursion: static int factorial(int n) { if(n == 0 || n == 1) // base condition return 1; else return n * factorial(n - 1); } public static void main(String[] args) { int result = factorial(5); System.out.println(result); } #Java #Programming #SoftwareDevelopment #JavaDeveloper #Coding #ProblemSolving #LearningJourney #ComputerScience #KodNest

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories