Manas Saxena
Manas Saxena

Reputation: 2365

Initializing a variable in Recursion

My code is below:

public int workTimeSum(list of parameter){

    int i=0,sum=0,flag=-1;
    boolean b=true;
    Stack<NonOverlapIntervals> str;

    if(st.size()!=1){
        b=recursiveCheck(non_overlap_list,st,Ioj);

        if(b==false){
            st.pop();
        }

        System.out.println("now size is:"+st.size());
    }

    str=(Stack<NonOverlapIntervals>) st.clone();
    System.out.println("Stack is ss");
    while(!str.empty()){
        System.out.println(str.pop().self_id);
    }

    if(b || st.size()==1){
        for(NonOverlapIntervals obj:non_overlap_list){
            i++;

            if(obj.id==ids){

                if(st.size()!=1 && object_Present(st,obj)){

                    continue;
                }
                else{
                    st.push(obj);
                    sum=workTimeSum(non_overlap_list,obj,st,obj.self_id,i);

                    if(sum_max<sum)
                        sum_max=sum;
                }
            }
        }
        flag=1;
    }
    else{
        return 0;
    }

Above is a recursive code.

What you need to see in the above code is only sum, sum_max variable.

I am computing the sum and checking if it's greater than sum_max each time a sum is computed.

But as I have initialised sum_max to zero after each call my sum_max becomes 0;

The problem is eliminated if I declare sum_max as global variable. But i am not allowed to use global variable.

I also tried passing sum_max a parameter of the recursive function but that won't work.

Upvotes: 0

Views: 3195

Answers (2)

William Falcon
William Falcon

Reputation: 9813

You can initialize the variable without needing a second method if you just check to see if it is null if so, initialize it and pass it to the next method (so it will be initialized)

//very basic endless example
public void myRecursiveMethod(Object var){

    if (var==null){
      var = new Object();
    }

    myRecusivemethod(var);
}

Upvotes: 1

Robin Green
Robin Green

Reputation: 33063

I think the answer lies in the way you have phrased the question. You misunderstand: you don't initialise a variable while you are recursing. You only initialise it once.

To do this, it may sometimes be helpful to create another method for the first step ("base case") of the recursion, which does the initialisation.

However, the code you posted doesn't actually match what you describe to be the case. In the code you posted, you don't initialise sum_max at all. So I'm confused.

Upvotes: 0

Related Questions