SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Recursion
Exercise:
Exercises
Question:2 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.