Home > Software design >  if/else statement with arrays is failing
if/else statement with arrays is failing

Time:05-29

So the code is really simple, its just a main(), but there is something wrong in the if/else statement in the while cycle and I dont't know what it is, I thought this is how it supposed to work, but clearly its not.

The code is creating a 11-element array, but the 0th element of the array is typed in by the user. So for example I type in 5, the array have the numbers from 5 to 15. Then the program shows you the numbers in the array. Then you can type in any numbers, and if your number is equal to any of the numbers in the array, then the program should say: "YEES!!!".

The problem is, the program always says, what it should only if the input number is not equal to any number in the array...

So can please someone explain me why the if/else statement is failing?

I also wrote this in Code::Blocks if that changes something...

The code:

#include <iostream>
using namespace std;

int main(){
    int numbers[11];
    int input;

    cout << "Type in a number: ";
    cin >> input;

    for (int i=0; i<11; i  ){
        numbers[i] = input  i;
    }

    for (int i=0; i<11; i  ){
        cout << numbers[i] <<endl;
    }

    while (true){
        cout<<endl;
        cout << "Type in a number:" <<endl;
        cin.sync();
        cin >> input;
        if (input <= numbers[11] && input >= numbers[0])
            cout << "YEES!!!" << endl;
        else{
            cout << "Number is out of range!" <<endl;
            cout << "Please try again!" <<endl;
        }
    }

    return 0;
}

CodePudding user response:

Indexing starts with zero, so if you create an array with a size of N last index always will be N-1. In your case, the index of the last element is 10.

if (input <= numbers[10] && input >= numbers[0]) // accurate

CodePudding user response:

The last element in your array should be 10, not 11 because you start at zero. Try doing

if (input <= numbers[10] && input >= numbers[0])
  • Related