Write a method called writeNums that takes an integer n as a parameter and prints to the console the first n integers starting with 1 in sequential order, separated by commas. For example, consider the following calls:
writeNums(5);
System.out.println(); // to complete the line of output
writeNums(12);
System.out.println(); // to complete the line of output
These calls should produce the following output:
1, 2, 3, 4, 5
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Your method should throw an IllegalArgumentException if passed a value less than 1.
package recursion;
public class WriteNums {
public static void writeNums(int value) {
if (value == 1) {
System.out.print(1);
return;
}
if (value < 1)
throw new IllegalArgumentException();
// the funtion calls n times and store the values in java's call stack
writeNums(value - 1);
/*
* java internal call stack stores values in FIFO manner, till base case
* reached. FIFO works in such a way that whichever stores in the last index
* will be printed in the first index. Above recursion will fail if you pass an
* integer big enough,it will cause java's call stack to throw
* StackOverFlowException. I could've used an array to store the values and
* print in reverse to serve our purpose but then you won't under stand the java
* intenal stack.. play with writeNums method by passing some bigger numbers
*/
System.out.print(", " + value);
}
public static void main(String[] args) {
int n = 10;
System.out.println("Integers from 1 to "+n+ " are: ");
writeNums(10);
}
}
Output:
Integers from 1 to 10 are:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10