0

When i make ArrayList with size 5 it gives wrong result but when it becomes bigger than 5 it becomes correct!

#include <iostream>
#include <string>

using namespace std;

class list
{
    typedef int ListElemtype;
private:
    ListElemtype listArray[6];
public:
    bool insert(ListElemtype e)
    {
        if (numberOfElements == 5) //It turns wrong result when ListArray equal 5??
        {
            cout << "Can't do the insertion" << endl;
            return false;
        } //Why it return false? I know why i but = instead of == :D
        else
        {
            listArray[numberOfElements + 1] = e;
            numberOfElements++;
            cout << "Done perfectly!" << numberOfElements << endl;
            return true;
        }
    };

    bool first(ListElemtype &e);
    bool next(ListElemtype &e);
    int numberOfElements;
    int CurrentPosition;

    void LIST ()
    {
        CurrentPosition=-1;
        numberOfElements=0;
        return;
    }
};

int main()
{
    list A;
    A.LIST();
    A.insert(10);
    A.insert(20);
    A.insert(30);
    A.insert(40);
    A.insert(50);
    A.insert(60);
    system("pause");
    return 0;
}
2
  • Your indexing is all wrong. your list starts from 1 and not 0 Commented Apr 30, 2011 at 19:50
  • I think you might want to pay more attention to your formatting. It's making the code harder to read than no formatting at all... Commented Apr 30, 2011 at 19:51

3 Answers 3

1

Arrays are indexed from zero, not from one. So listArray[numberOfElements+1]=e; should be listArray[numberOfElements]=e;. The first inserted element goes into listArray[0].

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

1 Comment

Yeah thanks! Can you show me what happen when i made it listArray[numberOfElement]=e and make listArray[4] it gives Done Perfectly for all the results!
1

Your listArray size is 6 therefore array index would start from 0 till 5. When you have numberOfElements==5 with listArray[numberOfElements + 1] you are trying to store at index 6 which you don't have.

Comments

0

As you may know, C bases its arrays at 0 and not 1. Thus,

 else { listArray[numberOfElements+1]=e;

writes to the end of the array contained within list A, when numberOfElements is equal to 5 or higher.

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.