returning the number of elements in a list

I am given an array with n elements but need to write a function where it returns n-1 elements. Do I need a loop for this? Or must I write a prototype...

Here is what I have thus far:

[code]
//given array with 5 elements function must return value 4 elements since -1 is a special character
//length of list is finite
//



#include <iostream>

using namespace std;

int main ()
{
int array [] = {1, 4, -1, 3, 2};

cout << "The array has " <<sizeof (array)/ sizeof (int)<< " elements"<< endl;
return 0;
}
Your problem description is vague.

Are you trying to create a new array that does not contain the "special" element -1?

Are you trying to modify the existing array so that it does not contain the "special" element -1?

Are you trying to find the number of "special" elements (like -1) in the array? (And, if I understand correctly, report the number of non-special elements in the array?)
Given an array :
A[0]= 1
A[1]= 4
A[2]= -1
A[3]= 3
A[4]= 2

I must write a function that will return the number of elements provided that for each item in the list, the location of the next sequential entry in the list is stored as the value of the current item.
That is:
The function will return the value 4:
A[0]:= 1 ==> A[1] :=4 ==> A[4] := 2 ==> A[2] := -1
1 2 3 4
= 4 elements.

Is that clear enough? I already have a start, I just need some more guidance.
Thanks
Yes, that makes it clear, though you are not being explicit about your list's structure.

Your array is not just an array -- it is a linked list. Each element (or "node") is the index to the next element (or node) in the list.

Your task, then, is to simply count the number of nodes linked into the list. Anything negative (like -1) is not a valid array index, and so it is a terminating value.

Here's the issue: In most linked-list implementations (including array-based ones, like yours), the final node is part of the list. Hence, your example list contains five nodes, not four.


Alas, I haven't more time ATM. If no one responds before later, I'll post again.
Thank you so much. Since I'm only beginning to learn the language, I will look up some terms you mentioned. However, I'll be awaiting your feedback.

Thanks.
The basic principle is:

1
2
3
4
5
6
index of current node = 0;
while (index of current node is valid)
{
  counter++;
  index of current node = index of next node;
}

Hope this helps.
Topic archived. No new replies allowed.