Home > Back-end >  Convert while loop to recursive
Convert while loop to recursive

Time:04-10

I have the following code and I want to make the while loop recursive since I need a recursive function of the nth root of a number but I don't know how to do it

public static void main(String[] args) {
    float x = 0f;
    int n = 0;
    float result = 0f;
    float aux = 0.00001f;
    Scanner sc = new Scanner(System.in);

    x = sc.nextFloat();
    n = sc.nextInt();

    if (n == 0) {
        result = 1;
    } else {
        while (nthPower(result, n) < x) {
            result = result   aux;
        }
    }

    System.out.printf("%.4f\n", result);
}

public static float nthPower(float x, int n) {
    float tmp = 1;

    for (int i = 0; i < n; i  ) {
        tmp = tmp * x;
    }

    return tmp;
}

CodePudding user response:

Actually, you should break the function down first:

A loop has a few parts:

  • the header, and processing before the loop. May declare some new variables

  • the condition, when to stop the loop.

  • the actual loop body. It changes some of the header's variables and/or the parameters passed in.

  • the tail; what happens after the loop and return result.

foo_recursive(params){
    header
    return foo_recursion(params, header_vars)
}

foo_recursion(params, header_vars){
    if(!condition){
        return tail
    }

    loop_body
    return foo_recursion(params, modified_header_vars)
}
  •  Tags:  
  • java
  • Related