Accept Duplicate Input In Array



I create a simple program wherein the program will accept duplicate input from the user. A variable name limit will check if the user exceed from entering a duplicate input. It works fine in the first try but if i input another number with the same number from the last input the error always pop-up even i already reset the value of the variable limit. I'm stuck and i don't know where i went wrong with my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 #include <iostream>

using namespace std;

int main() {
  int rear = 0, limit = 0;
  int res[rear];

Start:
  cout << "\n\t Enter a number :  ";
  cin >> res[rear];

  for (int i = 1; i <= rear; i++) {
    if (res[rear] == res[i]) {
      limit++;
      if (limit >= 2) {
        cout << "\n\n Error: The number you input is already thrice ";
        system("pause");
        limit = 0;
        goto Start;
      }
    }
  }
  rear++;
  cout << " Run the Program Again ? ";
  cin >> choice;
  system("pause");
  goto Start;
  return 0;
}
1. Could you replace the goto with loop(s)?

2. Line 7: you create an array that has 0 elements. That is all that it will ever have.

3. Line 11: you read into nonexistent array element, and you don't even know yet, whether you want to store the value in the array.

4. Array indexing starts from 0, not 1.


Your biggest problem is that you don't have an array to store the values in. You write to out-of-range memory locations that causes undefined behaviour.
Topic archived. No new replies allowed.