Explaining about prints output ordering of recursive loop? - java

Can anyone please explain the print order of the recursive loop?
import java.util.Scanner;
public class DecimalToBinary {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int decimalNum;
int base;
base = 2;
System.out.println("Enter a nonnegative integer in decimal: ");
decimalNum = console.nextInt();
System.out.println();
System.out.println("Decimal " + decimalNum + " = ");
decToBin(decimalNum, base);
System.out.println(" binary");
}
public static void decToBin(int num, int base) {
if (num == 0) {
System.out.print(0);
} else if (num > 0) {
decToBin(num / base, base);
System.out.print(num % base);
}
}
}
Num % base must print reverse order like this:
why is the order of calls as shown? (Please help me revise my question, English is my foreign language)

Your printing occurs after the recursion. Using (25, 2) as an example, the order of your calls with printing looks like
decToBin(25, 2):
decToBin(12,2):
decToBin(6,2):
decToBin(3,2):
decToBin(1,2):
decToBin(0,2):
print(0)
print(1%2)
print(3%2)
print(6%2)
print(12%2)
print(25%2)
Removing the recursive calls and just leaving the print statements shows the order you are getting:
decToBin(25, 2):
print(0)
print(1%2)
print(3%2)
print(6%2)
print(12%2)
print(25%2)
If you want the printing to be in the reverse order, move the print statement before the recursive call:
public static void decToBin(int num, int base) {
if (num == 0) {
System.out.print(0);
} else if (num > 0) {
System.out.print(num % base);
decToBin(num / base, base);
}
}
New recursion with printing:
decToBin(25, 2):
print(25%2)
decToBin(12,2):
print(12%2)
decToBin(6,2):
print(6%2)
decToBin(3,2):
print(3%2)
decToBin(1,2):
print(1%2)
decToBin(0,2):
print(0)
New output:
decToBin(25, 2):
print(25%2)
print(12%2)
print(6%2)
print(3%2)
print(1%2)
print(0)

the order of the output is reversed
because once the dectobin function is called
decToBin(int num, int base) {
if (num == 0) {
System.out.print(0);
} else if (num > 0) {
it reaches the line
decToBin(num / base, base);
where it postpones its execution and calls "another instance" of the dectobin function with decreased number parameter, before getting a chance to output anything(in the code below)
System.out.print(num % base);
}
then this subsequent call of dectobin is stopped at the same line and another "instance" is started with even smaller num. and so on and so on. none of the "instances" so far gets a chance to print anything.
at some point the "instance" of the function which was started last, recognizes that its
num argument has decreased under value of 1; and since num is integer type, once it is positive but less than 1 it is "Rounded" to 0. so that the following condition is true:
if (num == 0) {
System.out.print(0);
then this last instance behaves differently from all its predecessors. instead of postponing its execution and creating a new "instance" it prints '0' in the line above and just ends returning the execution point to the one "instance" which called it, which then continues to run from the line it was postponed.
then this "instance" outputs its number
system.out.print(num % base);
and ends itself returning the execution to the one which was starting it. and so and so on.
the bottom line is: the function "instance" which started last had the first output.the one which started first had the last

Related

I am making a histogram

I am trying to make a histogram with inputting a value and rounding it. The rounded value should print out the number of asterisks.
I did the following code and inputted a value but, the output is coming out as nothing.
public class Histogram
{
public static void main(String args[])
{
histogram obj = new histogram();
obj.histogram(13.5);
}
}
class histogram
{
public void histogram(double num)
{
int roundNum = (int)(num);
if (roundNum == 14)
{
System.out.println("**************" + num);
}
if (roundNum == 3)
{
System.out.println("***" + num);
}
if (roundNum == 16)
{
System.out.println("****************" + num);
}
if (roundNum == 0)
{
System.out.println("" + num);
}
if (roundNum == 1)
{
System.out.println("*" + num);
}
}
}
In Java, typecasting to primitive type int from primitive type double can be thought of as simply removing the decimal part.
For example;
System.out.println((int) 13.1); // prints 13
System.out.println((int) 13.5); // prints 13
System.out.println((int) 13.9); // prints 13
So, when you call obj.histogram(13.5); with the function parameter num being 13.5, the operation int roundNum = (int)(num); is the same as int roundNum = (int)(13.5);, and assigns 13 to the roundNum variable.
Since no if statements handle this case (roundNum being 13), no output is generated.
On another note, hardcoding a lot of if statements for checking the same variable over and over again can usually lead to unnecessarily complex, inefficient and hard-to-read code. Can you think of a better way to print "*" characters for the histogram, by using the roundNum variable? (Hint: try experimenting with for loops)
Change your int roundNum = (int)(num); to int rounded = Math.round((float)num); it should give you the desired output.

Recursion - Exception in thread "main" java.lang.StackOverflowError

I am required to write a recursive method. I have written the code to perform the task without recursion. I am getting the error Exception in thread "main" java.lang.StackOverflowError at Exercise13r.recursion(Exercise13r.java:29). Code is... to enter a number then if result is even, divide by 2, if result is odd, multiply by 3 and subtract 1. Obviously I am looping but not sure why. Any assistance would be appreciated.
import java.util.Scanner;
public class Exercise13r
{
public static void main(String[] args)
{
// Initialize variables
long number = 0;
Scanner in = new Scanner(System.in);
System.out.println ("Enter a starting number: ");
number = in.nextInt ();
System.out.println ("Your starting number is: " + number);
if (number != 1)
{
recursion(number);
}
}
public static void recursion(long n)
{
if (n % 2 == 0)
{
recursion(n/2);
}
else
{
recursion(n*3-1);
}
System.out.println ("number: " + n);
return;
}
}
Your base case if (number != 1) needs to be inside the definition of the function so that it actually knows when to stop. Right now your program eventually reduces to calling recursion(1) and your function will still call itself recursively (what else can it do?) so it ends up calling recursion(2) which leads to recursion(1) again and so on.
Note that this becomes apparent if you move System.out.println ("number: " + n); before the recursive calls. Since you have infinite recursion it never gets around to printing anything preventing you from seeing the problem.
Here is a minimal working example:
class Exercise13r {
public static void main(String[] args) {
recursion(12);
}
public static void recursion(long n) {
System.out.println ("number: " + n);
if (n != 1) {
if (n % 2 == 0) {
recursion(n/2);
} else {
recursion(n*3-1);
}
}
}
}
Output:
number: 12
number: 6
number: 3
number: 8
number: 4
number: 2
number: 1

I am getting a Cannot find symbol error that I can't resolve

I am getting this error that to me looks like I am not calling the method correctly. I have reviewed the past answers here but none have specifically addressed my problem as far as I can see. This is for a class project. I realize my math in the method is most likely not correct yet but I need to get the rest working then deal with an incorrect out put. Thanks a lot!
Here is my code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse);
}
public static int reverse(int num, int rNum) {
rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}
And My error Message:
PrintOutNumbersInReverse.java:28: error: cannot find symbol
System.out.println ("Your number in reverse is: " +reverse);
^ symbol: variable reverse location: class PrintOutNumbersInReverse 1 error
Change method implementation to:
public static int reverse (int num)
{
int rNum = 0;
...
return rNum;
}
and place, that is calling this method to:
System.out.println ("Your number in reverse is: " +reverse(num));
Then should be fine
When copy pasting this into eclipse, i noticed 2 things:
1.) your reverse() method doesn't return an int, but it should because the signature of the method says so: public static int reverse(int num, int rNum). Maybe return rNum, or whatever the logic behind it might be?
2.) second, you have not declared any reverse variable in the main method. Maybe you wanted a parameterized call of reverse()?
Also it looks like, you want in the reverse() method rNum to be an output parameter. In java you can't pass primitives by reference, so whatever you do with rNum inside the method, the changes will only be present in the scope of the method. So you might want to calculate something and actually return the results of your calculations.
You need to use reverse as a method, and not a variable. Also, you are passing in a variable that is not used: rNum. You see in reverse(int num, int rNum); right after you start, it sets your rNum to 0. So why pass a number in that will get set to zero?
I did this from my phone, but this should be working code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse(num)); //<-- notice how this is a method cause it has "()"
}
public static int reverse(int num) { //<-- this has "int num" in the "()". This is a parameter.
int rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}

Having errors with Java assignment

I'm getting some errors in code I wrote for an assignment, and I can't quite understand them.
I:\Java Programming\FibonacciJDialog.java:19: error: variable sum might not have been initialized
return sum;
^
I:\Java Programming\FibonacciJDialog.java:20: error: unreachable statement
JOptionPane.showMessageDialog(null,"That Fibonacci Number is" ); // Display results in dialog box.
^
I:\Java Programming\FibonacciJDialog.java:25: error: missing return statement
}
^
3 errors
Tool completed with exit code 1
Here is the code:
import javax.swing.JOptionPane;
public class FibonacciJDialog {
public static long main(String[] args) {
String num;
int n;
int sum;
num = JOptionPane.showInputDialog("Enter n: "); // getting user number input.
n = Integer.parseInt(num);
Fibonacci box = new Fibonacci(); // Creating new Fibonacci object.
JOptionPane.showMessageDialog(null, "That Fibonacci Number is"); // Display results in dialog box.
return sum;
System.exit(0); // Terminate
}
}
This is the Fibonacci class I made.
public class Fibonacci {
int Fib(int n) {
int in1 = 1, in2 = 1;
int sum = 0;//initial value
int index = 1;
while (index < n) {
// sum=the sum of 2 values;
// in1 gets in2
// in2 gets sum
// increment index
}
return sum;
}
}
You never assign a value to sum.
sum = box.fib(n);
In your main function, you also return the value instead of outputting it to the console.
JOptionPane.showMessageDialog(null,"That Fibonacci Number is" + sum);
A few errors I've noticed:
You don't assign sum a value. It's only declared, but not initialized. That's what the stack trace tells you - you have to initialize the value to something.
I'm willing to bet that the "unreachable code" is a red herring - after you initialize your variable I don't see any code path that won't take you to newing your Fibonacci class.
For some reason, you've decided to return long from main(). I'm not sure how that's working - you may have some other main method somewhere else that calls this class - but you can either return a long, or set the signature of the method to void.

Utilizing recursion to compute a series

I must be failing to wrap my head around the concept of trying to store a value in a recursive method. Solving this using iteration would take seconds, but I am struggling with the recursive call. Basically I am trying to solve: 1/1 + 1/2 + 1/3 ...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter in the end number for the sequence: ");
int endpoint = input.nextInt();
System.out.println("The value of the sequence is : " + calcSequence(endpoint));
}
public static double calcSequence (int index){
if (index == 0)
return 0;
else
return (1/index) + calcSequence(index - 1);
}
You need to add some explicit type conversions. Your 1/index is being performed as integer division, and your call is losing all its precision. Simply changing this to 1.0/index (or 1d/index to indicate that the 1 should be used as a double) should get you what you're looking for.

Categories

Resources