0

I am trying to use an array in an if statement to determine whether the value of x is rare or not.

If I do it this way everything is common.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    int y[5] = {1,2,3,4,5};
    srand(time(0));
for(int z = 0; z <= 50; z++){
    int x = 1 + (rand()%6);
    cout << z;
    cout << " " <<x;
    if(y[5] == x){
        cout << ": Common" << endl;
    }else{
        cout << ": RARE" << endl;
    }
}

But if I do it this way everything is rare.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    int y[5] = {1,2,3,4,5};
    srand(time(0));
for(int z = 0; z <= 50; z++){
    int x = 1 + (rand()%6);
    cout << z;
    cout << " " <<x;
    if(y[5] == ++x){
        cout << ": Common" << endl;
    }else{
        cout << ": RARE" << endl;
    }
}

I am really stumped on what to do can someone please help me?

2
  • You're accessing the array out of bounds in both cases. Commented Aug 14, 2014 at 4:40
  • Indexes start at 0, so y[5] is already out of bounds of your 5-element array. Commented Aug 14, 2014 at 4:42

2 Answers 2

1

You are also accessing the array in position 6 (out of bounds) in both cases. You are simply lucky that the first one works, but not the second one.

Change it to y[4] (array indexing starts at 0).

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

Comments

1

Your program has undefined behavior. y[5] is accessing the array out of bounds.

Use y[N-1] to access the last element of an array of size N, so here you should use y[4]

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.