c++ - Negative value not being added to Array -


problem

i have 2 arrays, 1 positive numbers, 1 negative numbers. reason, if first number added negative number, creates array space add number yet number inserted 0.

code adding

here add method, determines if value negative or positive , adds value appropriate array:

bool myclass::addint(int valuetobeinserted){   if (valuetobeinserted >= 0){     if (posarrayiterator >= sizeofmyarray){       return false;     } else {       cout << "added " <<  valuetobeinserted << "\n" << endl;       myparray[posarrayiterator] = valuetobeinserted;       posarrayiterator ++;       return true;     }    } else {     if (negarrayiterator >= sizeofmyarray){       return false;     } else {       cout << "added " <<  valuetobeinserted << "\n" << endl;       mynarray[negarrayiterator] = valuetobeinserted;       negarrayiterator ++;       return true;     }   }  } 

output

with following test:

b.addint(-1); b.addint(-3); b.addint(-9); 

the expected output be

[-1, -3, -9]  

but output

[-3, -9, 0]. 

any appreciated.

since not posting whole class can guess problem is.

1) posarrayiterator , negarrayiterator initialized 0? should be!

2) value of sizeofmyarray?

there nothing wrong bool myclass::addint(int valuetobeinserted)

see example below:

class  myclass {  private:  int sizeofmyarray;  int posarrayiterator;  int negarrayiterator;  int mynarray[20];  int myparray[20];       public:  myclass(){      sizeofmyarray = 20;      posarrayiterator = 0;      negarrayiterator = 0;   };   bool addint(int value);   void printnarray()  {    cout << "[ ";    (int i=0; i<negarrayiterator; i++)    {      cout << mynarray[i];      if ( (i+1) < negarrayiterator )       {          cout << ", ";       }    }    cout << "]";  } };   bool myclass::addint(int valuetobeinserted){   if (valuetobeinserted >= 0){     if (posarrayiterator >= sizeofmyarray){       return false;     } else {       cout << "added " <<  valuetobeinserted << "\n" << endl;       myparray[posarrayiterator] = valuetobeinserted;       posarrayiterator ++;       return true;     }   } else {         if (negarrayiterator >= sizeofmyarray){             return false;         }         else {            cout << "added " <<  valuetobeinserted << "\n" << endl;            mynarray[negarrayiterator] = valuetobeinserted;            negarrayiterator ++;            return true;       }  } }  int main()  {   myclass b;   b.addint(-1);   b.addint(-3);   b.addint(-9);   b.printnarray();   return 0;  } 

output:

added -1  added -3  added -9  [ -1, -3, -9] 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -