recursion program to add and subtract a number - java

I want to implement this program but it throws errors on every function call and runs an infinite loop.
class abc
{
public static void main(String[] args) {
int n=16;
calll(n);
}
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
n=n+5;
calll(n);
return n;
}
}
}

There is no end condition to your function.
Whether n is greater than 5 or not you run the calll function, which then runs the calll function again to infinite.
You need a conditon that will end the recursion, for instance changing the call function to this:
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
return n;
}
}
However the function is still rather pointless as you don't actually do anything with n. Keep in mind that the n that you define in the main function is never modified.

Related

Use counter to keep track from a function to global level

public static void main(String args[]){
extract("e:\\");
}
public static void extract(String p){
File f=new File(p);
File l[]=f.listFiles();
int counter = 0;
for(File x:l){
if(x.isDirectory()) extract(x.getPath());
else if(x.getName().endsWith(".mp3"))){
counter = counter + 1;
}
}
// I want to count and return value at last
}
Using this method(above), resets the counter every time when for loop ends.
So here, I want to count even when the for loop ends so that I can keep track of the number of .mp3 files.
I want to count and return value at last.
Return the current counter and make sure you add the response when you call recursively back to the counter.
public static void main(String args[]) {
int count = extract("../");
}
public static int extract(String p) {
File f = new File(p);
File l[] = f.listFiles();
int counter = 0;
for (File x : l) {
if (x.isDirectory()) {
counter += extract(x.getPath());
} else if (x.getName().endsWith(".mp3")) {
counter++;
}
}
return counter;
}
You should not use recursion like that. (Recursion should always have a termination condition to avoid running in a loop forever!
I think the problem is, that you create new Integers every time you call your method, so you will eventually override your old value or even use many different Integers to count.
You can wrap everything in a class in which you keep track of one integer.
Some pseudo-code:
public class Mp3Counter {
private int numberOfMp3 = 0;
public void extract(...) {
if (foundMp3) {
this.numberOfMp3 += 1;
}
}
}

Printing integers in the ascending order recursively

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?
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
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:
When to stop the recursive call
Processing before making the recursive call
Processing before making the recursive call
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).
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);
}
}

return statement does not ending method java

public class Interpolation_search {
public static void main(String...s) {
int rr[]= {1,2,3,4,9,10,15,80};
System.out.println(search(rr,0,7,3));
}
static int search(int ar[], int lo, int hi,int X) {
if(lo<hi&&ar[lo]!=ar[hi]) {
int mid=lo + ((hi-lo)/(ar[hi]-ar[lo]))*(X-ar[lo]);
if(X==ar[mid])
return 1; //l1
else if(X>ar[mid])
search(ar,mid+1,hi,X);
else search(ar,lo,mid-1,X);
}
return 0; //l2
}
}
return is executing twice first at l1 and second at l2.
It seems that you have difficulties understanding recursion.
Your method search() is supposed to return an int result. And the method itself calls itself (using different arguments) repeatedly. Thing is: you are all ignoring these recursive calls.
In other words: the real answer is for you to step back and understand what recursion is meant to be, and how to properly use it. As a starter, you could try to change
search(ar,mid+1,hi,X);
to
return search(ar,mid+1,hi,X);

Passing value from inside while loop to different class

So let's say I have a main class with a while loop:
public class Main {
public static void main(String[] args) throws InterruptedException {
int one = 1;
int counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
Function.Move();
one++;
}
The counter variable in this loop is counting each second elapsed.
There is a separate class called Function:
public class Function {
public static int Move (int result){
result = 1 + counter;
return result;
}
}
So as you can see, inside the Function class's Move method, I want to be able to use the counter variable's new value, which increases with each passing second, to calculate the value of a different variable which will then be returned to the main method.
The problem is that I can't figure out how to pass the value of counter to the Move method inside the Function class to begin with.
I'm not shure if i understand what you want to do correctly, depending on where exactly you will need that result variable later i think your coude should look something like this:
public class Main {
int counter;
public static void main(String[] args) throws InterruptedException {
int one = 1;
counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
one++;
}
}
public int getCounter() {
return counter;
}
}
public class Function {
public static int move (int result, Main main){
result = 1 + main.getCounter();
return result;
}
}
You can use Function.move() anywhere you need it's value in your Programm now.
Beware, though, that you will need your code using the Function.move() to run in a different Thread as the Main Thread. Otherwise it will always return 101 or 1, as the while loop will always be running before or after your call to Function.move(), depending on where you call it (except if you call it from within the while loop, but then you counld just use counter++ without the need to have an extra class)

Keeping count in a recursive Java method

Here's what I'm trying to accomplish with this program: a recursive method that checks if the number of instances of a substring matches a specified amount of instances, returning a boolean.
Here's the issue I'm having with this particular recursive method: I'd like to be able to move the counter inside the recursive method body, however, I ran into the issue that the counter resets at each recursive call when it is in the method body. The only way I have been able to make it work is through the use of a static counter variable declared outside of the function body. Is there any other technique I can marshall in order to be able to situate the counter of the method in the method body so that this method may act as a "black box"?
Thanks for any advice or insights you can provide.
public class strCopies {
//count instances of part and whole equality
static int count = 0;
public static boolean copies(String whole, String part, int check)
{
//check if current string length is valid
if(whole.length() < part.length())
{
//check if check parameter equals part instances
if(count == check)
{
return true;
}
else
{
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part))
{
count++;
}
//recursive call
return copies(whole.substring(1), part, check);
}
public static void main(String[] args)
{
System.out.println(copies("dogcatdog", "cat", 2));
}
}
You are almost there: you should change the meaning of the check variable to the remaining number of matches, rather than the original number requested. Then you can rewrite the method without keeping an additional count at all, as follows:
public static boolean copies(String whole, String part, int check)
{
//check if current string length is valid
if(whole.length() < part.length())
{
//check if check parameter equals part instances
if(check == 0)
{
return true;
}
else
{
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part))
{
check--;
}
return return copies(whole.substring(1), part, check);
}
You can pass the count as an argument to the recursive function, this way it will not be "reset" when the method is called.
public static boolean copies(String whole, String part, int check, int count)
{
//check if current string length is valid
if(whole.length() < part.length())
{
//check if check parameter equals part instances
if(count == check)
{
return true;
}
else
{
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part))
{
count++;
}
//recursive call
return copies(whole.substring(1), part, check, count);
}
public int countRecursive(String whole, String part){
if(whole.length() < part.length()) return 0;
if(part.length()==0) return -1; // ints can't express "Infinity"
// maybe you want to return -1 only if whole is not null, and something else if it is.
int count = 0;
if(whole.substring(0, part.length()).equals(part))
count = 1;
return countRecursive(whole.substring(1), part) + count;
}
public boolean count(String whole, String part, int check){
return countRecursive(whole, part) == check;
}
Note that this does away with the counter at the expense of creating a whole bunch of strings for each state. (You replace a single int with the length of each string given.) But then again, if you want performance then you shouldn't be using recursion for something like this. A simple for loop would do much nicer.
You could add the counter to the method parameters as follows:
public class strCopies {
public static boolean copies(String whole, String pargs, int check){
return copies(whole, pargs, check, 0);
}
public static boolean copies(String whole, String part, int check, int count)
{
//check if current string length is valid
if(whole.length() < part.length()) {
//check if check parameter equals part instances
if(count == check) {
return true;
}
else {
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part)) {
count++;
}
//recursive call
return copies(whole.substring(1), part, check, count);
}
public static void main(String[] args) {
System.out.println(copies("dogcatdog", "dog", 2));
}
}
The simple version:
Create a class that contain the counter.
Initialize it on your main.
Pass its reference to the function.
Another idea:
Create a singleton class with a static counter and your function X.
Inside its constructor add one to its counter and call function X.
Then instead of running your function like you did before, "create" that class, thus increasing the counter and calling the function.
The neat thing is you can inherit that class and redefine X to whatever you choose at a latter stage, so you get this general class that counts on each activation of a function.
Not sure what is your recursive method doing. However, to maintain a counter, you can pass it as an argument to your recursive method.
public boolean copies(String whole, String part, int check, int count) {
// your code here....
if(whole.substring(0, 3).equals(part))
{
count++;
}
//recursive call
return copies(whole.substring(1), part, check, count);
}
When you make first call to your copies method, you'll need to pass 0 to your count.

Categories