Reputation: 13
Today, I have taken an exam, and there was a question:
Write a method which prints integer numbers in the ascending order recursively from 1 to n:
public class PrintIntegersAscendingOrder {
static int counter = 0;
public static void PrintIntegersAscendingOrder (int n)
{
if (n == 1)
{
System.out.printf("%d\n", ++counter);
}
else
{
System.out.printf("%d ", ++counter);
PrintIntegersAscendingOrder(n-1);
}
}
public static void main (String args[])
{
PrintIntegersAscendingOrder(5);
}
}
Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?
Upvotes: 0
Views: 2289
Reputation: 4517
In your code you have defined in your class a method PrintIntegersAscendingOrder
having the same name of the class PrintIntegersAscendingOrder
containing it. This is an error that can be avoided for example renaming the including class to PrintIntegers
. Below the code of class without the error and with the recursive method:
public class PrintIntegers {
public static void PrintIntegersAscendingOrder(int n) {
if (n > 0) {
PrintIntegersAscendingOrder(n - 1);
System.out.printf("%d\n", n);
}
}
public static void main (String args[]) {
PrintIntegersAscendingOrder(5);
}
}
Upvotes: 0
Reputation: 78945
Do it as follows:
public class Main {
public static void printIntegersAscendingOrder(int n) {
if (n == 0) {
return;
}
printIntegersAscendingOrder(n - 1);
System.out.printf("%d ", n);
}
public static void main(String args[]) {
printIntegersAscendingOrder(5);
}
}
Output:
1 2 3 4 5
As @RobOhRob has already pointed out, the counter defeats the purpose of recursion in your code. When you are calling a function recursively, you need to analyse three important things:
Since you are already decreasing the parameter by 1
and passing it to the method to call it recursively, you can simply make use of this parameter instead of creating an additional variable (e.g. counter
).
Upvotes: 1
Reputation: 128
You can do it like this:
public class IntegerAscendingOrder {
public static void main(String[] args) throws Exception {
printIntegersAscendingOrder(n);
}
private static void printIntegersAscendingOrder(int i) {
if (i < 1) {
return;
}
printIntegersAscendingOrder(i-1);
System.out.println(i);
}
}
You don't need the counter variable in the class, using recursion you can limit the method call within the method itself.
Notice the if (i < 1) {return;}
line, this will terminate the recursive method call(s).
This article should help you Getting started with recursion
Upvotes: 3