is it posible to execute a line of code only once in recursive method

i just want to merge this 2 method in a single method

public double sum_family_age(){
double sum=0;
sum+=this.age; // add his/her own age
//recursively add his/her family age
if(children!=null){
for(Person value: children){
if(value!=null){
sum+=value.sum_family_age();
check++;
}
}
}
return sum;
}

public double average_family_age(){
double avg;
avg=sum_family_age()/family_size();
return avg;
}

can anyone suggest me thx.

Comments

  • : i just want to merge this 2 method in a single method
    :
    : public double sum_family_age(){
    : double sum=0;
    : sum+=this.age; // add his/her own age
    : //recursively add his/her family age
    : if(children!=null){
    : for(Person value: children){
    : if(value!=null){
    : sum+=value.sum_family_age();
    : check++;
    : }
    : }
    : }
    : return sum;
    : }
    :
    : public double average_family_age(){
    : double avg;
    : avg=sum_family_age()/family_size();
    : return avg;
    : }
    :
    : can anyone suggest me thx.
    :
    There are 2 ways to do this:
    1 create a non-recursive method, which calls the recursive method
    2 use a parameter to control what is done

    Here's an example of the second way:
    [code]
    public double sum_family_age(boolean calcAverage){
    double sum=0;
    sum+=this.age; // add his/her own age
    //recursively add his/her family age
    if(children!=null){
    for(Person valuechildren){
    if(value!=null){
    sum+=value.sum_family_age(false);
    check++;
    }
    }
    }
    if (calcAverage) {
    sum = sum/family_size();
    }
    return sum;
    }
    [/code]
    By calling this function with true as the parameter, you'll get the average of the family ages. With false only the sum.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion