I'm just curious why my application actually crashes after it compute the area of a cross.

I output is correct but it crashes after it calculation is done.

cross.cpp

void Cross::setCrossCord()
{
    for (int i=0; i<=12; i++)
    {
        cout << "Please enter x-ordinate of pt " << i+1 << ": "; 
        cin >> xVal;
        xvalue[i] = xVal;
        cout << endl;
        cout << "Please enter y-ordinate of pt " << i+1 << ": ";
        cin >> yVal;
        yvalue[i] = yVal;
        cout << endl;
    }
}


double Cross::computeArea()
{
    int points = 12;
    int running_total = 0;

    for (int i=0; i<12-1; i++)
    {
      running_total = (xvalue[i]*yvalue[i+1]) - (xvalue[i+1]*yvalue[i]);  //cross calculation of coord in a cross 
    }                                                                     //(x1*y2)-(y1*x1)

    running_total = (xvalue[points-1]*yvalue[0]) - (xvalue[0]*yvalue[points-1]);   // traverse back to the origin point
                                                                                   // (xn*y1)-(yn*x1)

    area = abs(running_total / 2); //purpose of absolute is to make sure result is positive. 
                                  //polygon are specified in counter-clockwise order (i.e. by the right-hand rule), then the area will be positive.

    return (area);
}

int main()
{
    Cross cross;
    string shapetype;

    cout << "enter shape type: " << endl;
    cin >> shapetype;

    if(shapetype == "cross")
    {
    cross.setCrossCord();
    }else
    {cout << "error" << endl;};

    cout << "area of cross is: " << cross.computeArea() << endl;
    return 0;
}

however if I change my for loop to

for(int 1=0; i<12; i++)

the calculation would actually be wrong.. why is this so?

There is an access violation actually. See at line 5 you have added 1 to i. So the storage of the xvalue array starts from 1 instead of 0. I know you were trying to show the output for what point the user inputting co-ordinates for. However you can start i from 1 in the for loop condition.
So like this:

void Cross::setCrossCord()
{
    for (int i=1; i<=12; i++)
    {
        cout << "Please enter x-ordinate of pt " << i << ": "; 
        cin >> xVal;
        xvalue[i] = xVal;
        cout << endl;
        cout << "Please enter y-ordinate of pt " << i << ": ";
        cin >> yVal;
        yvalue[i] = yVal;
        cout << endl;
    }
}

Then in the computeArea function start for loop also from 1 till 12.

Hope that works :)

This article has been dead for over six months. Start a new discussion instead.