Recursive Counting By Integers Up and Down - java

I received this assignment today and I am kinda stuck on it.
This is what the assignments say:
Write a method called recursiveUpAndDown() that takes one non-negative integer parameter, recursively starts at zero and prints all the integers from zero to the parameter (that is, prints 0, 1, 2, etc. all the way up to the parameter), then recursively starts at the integer parameter and prints all the integers from the parameter to zero (that is, prints the parameter, the parameter - 1, the parameter - 2, etc. all the way down to 0).
I was able to write the code for writing the coding to count down then up but unable to do up then down. Here is the code I wrote
class myCounter{
static void recursiveDownAndUp(int i)
{
if (i < 1)
return;
else
{
System.out.printf("%d ",i);
recursiveDownAndUp(i-1); // recursive call
System.out.printf("%d ",i);
return;
}
}
public static void main(String[] args)
{
recursiveDownAndUp(10);
}
}
We are not allowed to use 2 parameters, a helper method or a global variable. I know it seems hard, at least for me, but the professor said it is doable

static String recursiveUpAndDown(int n) {
if (n < 0) return "";
String x = recursiveUpAndDown(n - 1);
System.out.print(n + " ");
return n + " " + x;
}
public static void main(String[] args)
{
System.out.print(recursiveUpAndDown(10));
}

Related

How does recursion work and how can recursion be used to manipulate integer digits?

I'm trying to learn java, and I can't seem to understand recursion. I can understand how recursion can be used to add and do other basic math operations but how can recursion be used to reverse manipulate integers and individual integer digits.
example:
a method takes a single positive integer argument and displays its base five equivalent. 231 returns 1411 but the code below returns 1141. how would I reverse the order of integers put out?
public void base5(int n){
int rem=n%5;
int vis=n/5;
if(n!=0){
// System.out.print(rem/*+"|"*/);
//
// rem=(rem+rem)*10;
// System.out.print("\n||"+n+"||\n");
System.out.print(rem);
base5(vis);
}
else{
return;
}
}
The algorithm for getting individual digits of an integer, from right to left, is well known. See How to get the separate digits of an int number?.
I won't "explain" recursion, but I'll give you one possible solution for first problem:
a method takes a single positive integer and displays it with commas
inserted every three digits
import java.util.Scanner;
class Main {
public static void main( String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your positive integer: ");
long number = sc.nextLong();
String result = addCommas(number);
System.out.println(result);
}
public static String addCommas(long num) {
return addCommas(num, 1);
}
public static String addCommas(long num, int counter) {
if (num == 0) {
return ""; // base case ends recursion
}
else {
long digit = num % 10;
num = num / 10;
String comma = (counter%3==0 && num>0) ? "," : "";
// recursive call below because we call addCommas() again
return addCommas(num, counter+1) + comma + digit;
}
}
}
Here's a compact solution to the second problem:
a method takes a single positive integer and displays the result of
reversing its digits
public static String reverseDigits(long num) {
if (num == 0) {
return "";
}
else {
return String.valueOf(num % 10) + reverseDigits(num / 10);
}
}

Why does this while loop never terminate?

I am really stuck on understanding this one concept. I had a while loop from one of my exams, and even though I know what prints, I don't know why.
Here is the code:
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length-1);
}
}
public static void main(String[] args){
xMethod(5);
}
}
Because length is never updated.
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length - 1);
length--;
}
As the other answer have point it out, you need to decrements the length variable to fix your current problem with length = length - 1 or length--. (I let my "colleague" answer to explain it better).
My answer is mostly about you usage of a recursive method.
What you probably want is simple an if condition. The recursion will act as loop.
public static void xMethod(int length) {
length--;
System.out.print((length) + " ");
if (length > 1){
xMethod(length);
}
}
xMethod(5) > 4 3 2 1
public static void xMethod(int length) {
length--;
if (length > 1){
xMethod(length);
}
System.out.print((length) + " ");
}
xMethod(5) > 1 2 3 4
Length is not changing at all
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length-1);
//need to change the length here
}
}
public static void main(String[] args){
xMethod(5);
}
The important thing to add here is to understand how the assignments work in Java.
The value of length is not changed because when you pass a value in the method and it goes in the while loop, the loop stops when the condition stops but not the recursion xMethod(length-1); you have used. That's why even if you add length-- it will not print what you desire.
So for the program to work properly, you have to
Assign value to length variable
Change or remove the recursion.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
And once you go through the link, you will understand the why the value is not changing.
Note: From the link you come to know that length-- is equal to length = length -1, so basically we have to assign the updated value to length variable.
length is always have the value 5. you should replace length-1 by length--.
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length--) + " ");
xMethod(length);
}
}
public static void main(String[] args){
xMethod(5);
}
}

Trouble Understanding the Recursion Here

Can someone please help to explain to me why this ends up in an infinite recursion loop?
The variable length reaches the value 1 but for some reason the loop is still entered even though the loops condition is while (length>1).
I've tried printing values and running it over and over again, maybe I'm missing something more obvious or someone can explain this more simply. Thanks.
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length - 1) + " ");
xMethod(length - 1);
}
}
Additional info.
When I dubugged this code :
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length - 1) + " ");
xMethod(length - 1);
}
System.out.println("Coming out of while");
}
Below is the output :
4 3 2 1 Coming out of while
1 Coming out of while
1 Coming out of while
1 Coming out of while
1 Coming out of while
1 Coming out of while
1 Coming out of while
//repeated Infinite times
After coming out of while loop why it is going back in the same while loop with length as 2?
Edit: I appreciate all of your responses and understand that if I wanted to code something like this I would probably us an if statement as most recursive methods do but this is simply a question of me perhaps not understanding how the scope or call stack works. If I'm correct the while loop block holds on to the value of length as 2 no matter what happens outside of that block?
You are doing 2 things here. When you are writing a recursive code, you always need to think when the when code will end. Your code does not have a end case.
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
System.out.println("Method Start "+ length);
while (length > 1) {
System.out.println("Inside while "+ length);
xMethod(length - 1);
}
System.out.println("Method End "+ length);
}
}
Now this code produces the following output:
Method Start 5
Inside while 5
Method Start 4
Inside while 4
Method Start 3
Inside while 3
Method Start 2
Inside while 2
Method Start 1
Method End 1
Inside while 2
Method Start 1
Method End 1
Inside while 2
Method Start 1
Method End 1
Inside while 2
Method Start 1
Method End 1
.
.
As you can clearly see,
Inside while 2
Method Start 1
Method End 1
is repeated again and again.
So what this means is, when the length is 2, the following will happen.
while (2 > 1) {
System.out.println("Inside while "+ length);
xMethod(1);
}
The output for this is
Inside while 2
Now, xMethod(1) doesn't even enter the while loop, so this will be printed.
Method Start 1
Method End 1
But you should now understand that while(2>1) is again execute because the length has not changed and it is still 2.
while (2 > 1){
System.out.println("Inside while "+ length);
xMethod(1);
}
goes on and the loop continues.
Because you are not updating the value of length in the current method. The value is just decremented when sending to the method.
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length) + " ");
xMethod(length);
length--;
}
}
The variable length never reaches the value 1 in any loop, you mix two design and i think you need on of them, recursive method or loop.
first design:
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
System.out.print((length - 1) + " ");
if(length > 1)
xMethod(length - 1);
}
}
another way:
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length--) + " ");
}
}
you can select one of these, it depend on your design.
if it's not your answer, please write your expect output.
because when length reaches 2 xMethod(2) is called and therefore xMethod(1) follows, when xMethod(1) ends, since length is still 2 it again calls xMethod(2) and the this calls xMethod(1) it repeates..
to fix it, use return after xMethod(length - 1);
public static void main(String[] args){
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length - 1) + " ");
xMethod(length - 1);
return;
}
System.out.println("Coming out of while");
}

How to make my method accept x number of parameters [duplicate]

This question already has answers here:
When do you use varargs in Java?
(8 answers)
Closed 6 years ago.
I am faced with probably a very simple dilemma. I am trying to create a program that computes the averages, sums, and count of all numbers inputed to the calculator. The problem with this is that I can only accept one input or three (dependent on number of variables listed in my method parameters). How do I make my add() method actually accept n number of inputs as opposed to a predefined set?
Main Class
public class Calculator
{
public static void main (String [] args)
{
AverageCalculator calculation1 = new AverageCalculator();
AverageCalculator calculation2 = new AverageCalculator();
calculation1.add(13);
System.out.println("Sum: " + calculation1.getSum());
System.out.println("Count: " + calculation1.getCount());
System.out.println("Average: " + calculation1.getAverage());
System.out.println();
calculation2.add(3, 7, 12); // Error due to method parameters
System.out.println("Sum: " + calculation2.getSum());
System.out.println("Count: " + calculation2.getCount());
System.out.println("Average: " + calculation2.getAverage());
}
}
I get an error when compiling this:
Calculator.java:28: error: method add in class AverageCalculator cannot be applied to given types;
calc2.add(3, 7, 12);
I am then running into how am I going to deal with my add() method's functionality. I know what it must do, I am sure I must add a for Loop. However, there is no given length for it to parse. Do I have my i = 0; i < calculation 2; i++? See comments in this portion
Secondary Class
public class AverageCalculator
{
private int sum;
private int count;
public AverageCalculator () {}
public void add (int newNum) // One input due to single parameter
{
// How to accept the multiple input from main class with this mutator
// and successfully manipulate data in this method
sum += newNum;
count++;
}
public int getSum()
{ return sum; }
public int getCount()
{ return count; }
public double getAverage()
{ return (double) sum / count; }
}
Java supports this. Is is called "varargs". If you add "..." to your type, you can repeat it as many times as you want (including 0 times) and then, in your function, process it as an array. This could like this (this code is completely untested):
public void add(int... newNums) {
for (int num : newNums) {
sum += num;
count++;
}
}
A you can read a bit more here.

Printing text with spacing recursively

This is an assignment for school. I am having trouble understanding how I can print the following recursively:
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
This ALSO written by call number 4.
This ALSO written by call number 3.
This ALSO written by call number 2.
This ALSO written by call number 1.
I'm not sure if I am supposed to be illustrating a loop vs. recursion or if there is a way to print all of this recursively. Additionally, how would I go about reversing the recursion call so it starts from 4 as per the example output?
This is my current output.
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
This ALSO written by call number 1.
This ALSO written by call number 2.
This ALSO written by call number 3.
This ALSO written by call number 4.
There is no spacing implemented in the for loop yet b/c I'm not sure if that part is also supposed to be recursive.
My code:
public class Recursion {
public static void main(String[] args) {
for (int i = 2; i < 5; i++) {
System.out.println("This was written by call number " + i + ".");
}
recurse(4);
}
public static void recurse(int n) {
String temp = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (n < 2) {
System.out.println("This ALSO written by call number " + n + ".");
}
else {
recurse(n - 1);
System.out.println(temp + "This ALSO written by call number " + n + ".");
}
}
A simpler solution.
public static void main(String[] args) {
recurse(1);
}
public static void recurse (int n) {
if (n==5) return;
String temp="";
for (int i=0;i<n;i++) temp += " ";
if (n!=1) {
System.out.println(temp + "This was written by call number " + n + ".");
}
recurse(n+1);
temp=" ";
for (int i=0;i<n;i++) temp += " ";
System.out.println(temp + "This ALSO was written by call number " + n + ".");
}
The key to writing most recursive programs (especially the ones you're given as assignments) is to look for a larger problem that contains a similar but smaller occurrence of the same problem.
In your case, the "larger problem" would be to print the 6 lines that start and end with "call number 2". That is, print lines for call numbers 2 through 4. The way to do this is: print the first line that says "call number 2", solve the problem to print the 4 lines for call numbers 3 through 4, and print the last line that says "call number 2". The part in the middle is the smaller occurrence of the same problem. That's going to be the recursive call.
Since your larger problem is going to start with "call number 2", and your smaller problem is going to start with the call number that's one higher, I'd recommend arranging things so that you call recurse(n+1) instead of recurse(n-1). If you do that, you'll need a second parameter so that you know when to stop recursing--something like recurse(n+1, last).
Hopefully this will be enough to get you thinking on the right track.
Try this:
public static void main(String[] args) {
recurse(1, true, 1);
}
public static void recurse(int n, boolean loop, int add) {
String temp = "";
String out = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (add > 0) {
out = temp + "This was written by call number ";
} else {
out = temp + "This ALSO written by call number ";
}
if (n == 1 && !loop) {
System.out.println(out + n + ".");
return;
} else if (n == 1) {
recurse(n+add, false, add);
} else if (n == 5) {
add = add - 2 * add;
recurse(n+add, false, add);
} else {
System.out.println(out + n + ".");
recurse(n+add, false, add);
}
}
Here is quite a straightforward solution. Also pay attention how you can easily get the indent string (via substring). The recursion is as simple as it gets: print the number, enter the function with a larger number if below the max, then follow back.
class R{
static final String spaces=" ";
public static void main(String[] args) {
rec3(1,4);
}
private static void rec3(int i, int max) {
if (i>1) System.out.printf("%sThis was written by call number: %d%n", spaces.substring(0, i-1), i);
if (i<max) rec3(i+1, max);
System.out.printf("%sThis was ALSO written by call number: %d%n", spaces.substring(0, i-1), i);
}
}
Thanks to everyone for the help. I ended up modifying the solution from #JoseLuis a little bit.
public class Recursion {
public static void main(String[] args) {
recurse(1, 5);
}
public static void recurse(int n, int max) {
String temp = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (n == max) {
return;
}
if (n != 1) {
System.out.println(temp + "This was written by call number " + n + ".");
}
recurse(n + 1, max);
System.out.println(temp + "This ALSO was written by call number " + n + ".");
}
}

Categories