Variable keeps getting set to 1 at the end of recursion method - java

EDIT: Got it working. Still not sure what the weird issue was, but I think it had to do with the fact that I had a loop and recursion.

I don't fully understand the question. but you don't need both, a while loop and recursion. Recursion alone is sufficient here. Use a simple if statement to stop recursion when the number is fully printed.
Note that recursion simplifies putting the digits in the right order here -- with a while loop, you'd need to reverse them somehow...
public static void printInBinary (int num) {
int div = num % 2;
int rem = num / 2;
if (rem > 0) {
printInBinary(rem);
}
System.out.print(div);
}

Your while loop is continuously going because your num-- isn't in the loop, so the number never changes.
public static void printInBinary (int num)
{
int div = (Integer)num%2;
int rem = (Integer)num/2;
while (num >= 1)
{
System.out.print(div);
printInBinary(rem);
num--;//Moved here
}
//removed from here
}

Related

Returning max value in java

Pretty simple question I'm sure, since I'm only just learning.
In a larger class that I am on my way of implementing, we have to provide a method Max to return the maximum value in an array. This is what I have:
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
return Max;
}
}
However, the method does not compile. I believe it has something to do with the return type. The program calls up this function (and a similar Min function) like this further on in the program:
System.out.println("[" + window.Min() + " " + window.Max() + "]");
What am I doing wrong?
EDIT: Thanks for all of your answers! Just started learning coding, so trivial mistakes like this one can still cause a whole lot of frustration. Saving my ass, all of you!
Java always considers the possibility of the for loop not being entered, and sees no return statement at the end of the method, giving a missing return statement compiler error. The method is declared to return something, an int, so every possible execution path must return something.
Move return Max; after the end of the for loop, both to satisfy the compiler and to provide a correct "find the max" method.
Incidentally, Java variables usually have a lowercase first letter per normal conventions. The Max variable should be called max. The same applies to the name of the Max method.
I believe this does not compile because there's a way you can get to the end of the method without an explicit return statement.
You need to put that return Max; at the bottom, as opposed to inside the for loop:
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
}
return Max;
}
The return statement should not be in the for loop.
It should be
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
}
return Max;
}
It doesn't compile because it is possible to get to the end of the method without anything being returned. If the length of the array is 0 or 1 the loop will not be entered and the return not executed.

Sudoku Solving Algorithm

I have tried writing the algorithm by referring this.
But i am getting Error of StackOverFlow.
Help me out to find what is wrong in the program? Is it the recursion part?
public void beginSolving(int board[][],int x,int y){
int i = 1;
if(unassignedCell(board,x,y)){
board[x][y] = i;
if(isValidCell(board,y,x,i)){
board[x][y] = i;
}
if(!isValidCell(board,y,x,i)){
board[x][y] = 0;
i++;
}
} else {
while(x<9){
beginSolving(board,x++,y);
if(x==9){
x = 1;
beginSolving(board,x,y++);
if(y==9){
}
}
}
}
}
Look at the recursive calls: beginSolving(board,x++,y). The x and y parameters are the same as in the original call (remember that the value of x++ is the value before it is incremented). Thus it is likely that you enter a never ending recursion.
The while(x < 9) will never terminate since whenever x reaches 9 it is reset to 1.
The algorithm never tries to set a number other than 1 into the board.
There may be other problems with the code as well, I did not check it in detail.

Fibonocci Generation by Recursion

I am trying to create a method that will generate a Fibonacci sequence based on user input and calculated to the tenth number, all through recursion. (Learning recursion right now, this is one exercise).
Here is my attempted code, which I am currently struggling to make work:
//being run with fibonacci(10, 10);
//Start being the number the sequence starts with
public static int fibonacci(int start, int times)
{
if(times > 0)
{
int result = fibonacci(start - 1, times - 1) + fibonacci(start - 2, times - 1);
sequence += result;
return result;
}
System.out.println(sequence);
return start;
}
This, however, returns a large amount (I think about 40,000 numbers taking approximately 10 seconds to run to completion). Also all the numbers appear to be negative, definitely not what my aim was.
Now, on to identifying the problem: I believe the problem is that the method is calling itself twice more every single time it is called, adding up to the large amount. However, I can't think of a way around this seeing as I am trying to do it through recursion each time and I have no choice but to call it again.
As for why it is negative, I haven't a clue. I thought I was using the Fibonacci equation correctly, but obviously I am doing something incorrectly.
Could anyone help me through this please?
(True, I could easily google some code for this as I am sure it is out there, but I want to actually learn how this is done and what I am doing wrong for future reference. Better to advance as a programmer than to get the grade from copied code and move on)
I think you are a little confused here with what the Fibonacci sequence is. The formula is F(n) = F(n-1) + F(n-2). Recursion should always end at a base case which for Fibonacci is F(0) = 0 and F(1) = 1. Your method only needs one variable which is n.
Think about it this way:
public static int fibonacci(int n) {
//Insert your base cases here to terminate early
//Then process the recursive formula
return fibonacci(n - 1) + fibonacci(n - 2);
}
I think I understand what you are trying to do. You want 10 fibonacci numbers from start. Perhaps something like this will work:
public static int[] fibonacci(int start, int times)
{
return fibonacci(start, times, 0, 1, new int[times]);
}
private static int[] fibonacci(int start, int times, int a, int b, int[] answer)
{
if( start > 0 )
return fibonacci(start-1, times, b, a+b, answer);
if( times > 0 )
{
answer[answer.length - times] = a;
return fibonacci(start, times-1, b, a+b, answer);
}
return answer;
}
public static void main(String[] args) {
int[] a = fibonacci(5, 10);
for(int i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}

Printing fibonacci series in recursion

I am trying to print Fibonacci series using recursion and my code is not ending the recursion . Can you tell me if i missed something.I think the second recursion is going into infinite loop and i am not able to figure out why it is happening
class Main
{
public static void main (String[] args)
{
int k=7;
int x=0,y=1;
fib(x,y,k,0);
return;
}
public static void fib(int x,int y,int k,int cnt)
{
int z;
if(cnt>k)
return;
if(cnt<=k)
{
z=x+y;
x=y;
y=z;
System.out.println("value is"+z);
fib(x,y,k,cnt++);
}
}
}
You don't seem to understand the concept of Fibonacci Number. Please read the wikipedia article. Following is the code for this function.
public static int fib(int n)
{
if(n == 0 || n == 1)
return n;
return fib(n-1) + fib(n-2);
}
The issue is the post-increment in:
fib(x,y,k,cnt++);
This passes the original value of cnt to the recursive call, and then increments it.
If you print the value of cnt at the start of fib(), you'll see that it is always zero.
One easy fix is to change that call to
fib(x,y,k,cnt+1);
Also, your numbering of Fibonacci numbers is a bit odd (I'd say that the seventh number is 8 and your code thinks it's 34).
Finally, I may be worth noting that the second if is unnecessary.

Can anyone see where the infinite loop in my program is?

The purpose of this program is to find the smallest number evenly divisible by all integers 1 through 20. I know it could be made more efficient, but I'm not interested in optimizing it right now. When I execute the program, it seems to hang forever, which leads me to believe that there's an infinite loop somewhere. I can't seem to find it though. I'm not sure what part of the code is causing the problem and it's relatively concise, so I'll post it all here.
public class Problem5{
public static void main(String[]args){
boolean notFound = true;
while(notFound){
int n = 20;
if(testDivide(n)){
System.out.println(n);
notFound = false;
}
else
n++;
}
}
private static boolean testDivide(int target){
for(int i = 20; i > 0; i--){
if(target % i != 0)
return false;
}
return true;
}
}
If anyone can help me out with this, I'd appreciate it a lot.
Additional Information: The program also never outputs any numbers, which leads me to believe that if(testDivide(n)) is never evaluating to true.
You are initializing the value of n inside your while loop to 20, since n is always 20 for testDivide(20), which will always return false since 20 % 19 != 0 returns false. Hence remove int n = 20 from your while loop.
boolean notFound = true;
while(notFound){
int n = 20;
should be
boolean notFound = true;
int n = 20;
while(notFound) {
your for loop makes sure you return false, and then your while loop always sets i to 20 this is your infinite loop.
See the while loop:
while(notFound){
int n = 20;
if(testDivide(n)){
System.out.println(n);
notFound = false;
}
else
n++;
}
When the while loop is executed first, the value of n is set to 20.
the test divide returns false.
The value of n is decremented to 19.
The loop executes again
The value of of n is reinitialized to 20.
This is the problem initialize n outside the while loop.

Categories

Resources