1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Deleting element from array

  1. Mar 10, 2013 #1
    1. The problem statement, all variables and given/known data
    Hey all. I have code that is supposed to delete the offset determined by the user and shift the elements after that offset to the left. My code works fine except for one problem: if the index is zero it terminates. I will post my code, and if anyone can see why it is giving me this problem, I would greatly appreciate it!

    3. The attempt at a solution

    PHP:

    #include <iostream>
    using namespace std;

    int arrayA(int theArray[],int size)
    {
        cout << "Array: " << '{';
        int i = 0;
        while (i < size)
        {
            cout << theArray[i];
            if (i < size-1){cout << ',';}
            i++;
        }
        cout << '}' << endl << "Want to delete something (y/n)? ";
        char ansr;
        cin >> ansr;
        if (ansr == 'y')
        {
            cout << "Offset to delete? ";
            int offset;
            cin >> offset;
            return offset;
        }
        else if (ansr == 'n')
        {
            cout << "Goodbye!";

        }
        return 0;
    }

    int arrayB(int theArray2[], int size, int offset)
    {
        if ((offset >= size)||(offset < 0)){ cout << "Sorry, cannot delete that." << endl; return size;}
        for (int m = offset + 1; m < size; m++)
        {
            theArray2[m-1]=theArray2[m];
        }
        size--;

        return size;
    }



    int main() {
        int N = 10;
        int y;
        int fling[]={1,2,3,4,5,6,7,8,9,10};

        do{
        y = arrayA(fling, N);
        N = arrayB(fling, N, y);

        }while ((N > 0)&&(y != 0));



        return 0;
    }
     
     
  2. jcsd
  3. Mar 11, 2013 #2

    nvn

    User Avatar
    Science Advisor
    Homework Helper

    sandy.bridge: To repair your program, do the following.

    (1) Change your first "return 0;" to "return -999;".
    (2) Change 'cout << "Sorry, cannot delete that." << endl;' to 'if (offset != -999){cout << "Sorry, cannot delete that." << endl;}'.
    (3) Change "}while ((N > 0)&&(y != 0));" to "}while ((N > 0)&&(y != -999));".
    (4) Move 'cout << "Goodbye!\n";' to the end of main(), immediately before "return 0;".

    Try it, and see if it now works.
     
    Last edited: Mar 12, 2013
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted