0

My program adds a name and age attribute to a list of PERSONS. I'd like to have a function that passes the "first" and "last" pointer to this list. From here, I wanted the program to start from the first pointer and add that age to the next, and the next, until the last pointer is reached.

For example, if my list were:

Jane (36 yrs), Bob (14 yrs), Rachel (10 yrs)

I want it to sum up 36 + 14 + 10 = 60

Please help!

So far, i have the function prototype to be

int total_age(person **f, person **l)
{
   int sum=0;
   person *temp;
   sum = sum + person->age;
}

How do I run through each person.age value for from first to last?

2 Answers 2

1

Since you said this is a linked list, I'm assuming that each Person object has a pointer to the next person in the list. I'll call this Person->next. I'm also assuming that the next value of the last person in the list is NULL.

So then you just need to iterate through the list, adding the age at each node. This just involves creating a while loop (and adding a return statement):

int total_age(person **f, person **l)
{
   int sum = 0;
   person *temp = *f;
   while (temp != NULL)
   {
       sum = sum + temp->age;
       temp = temp->next;
   }
   return sum;
}

Note that you don't actually need the last item in the list to be passed to the function.

Sign up to request clarification or add additional context in comments.

Comments

0

Well, first of all you have to iterate over the linked list elements, for example:

int total_age(person *f)
{
  int sum = 0;

  for (person *p = f; p; p = p->next)
  {
    sum += p->age;
  }

  return sum;
}

If you're not planning to change the first and last pointers, then simply pass pointer to person, not pointer to pointer to person. Also, no need for pointer to last person.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.