-2

I am trying to check if a number is in an array in C++. The solution I have is kinda messy:

int luckynumbers[5] = { 3, 5, 8, 15, 19};

std::cout << "Enter number from 1 - 20: ";
int choice;

std::cin >> choice;
if (choice == luckynumbers[0] || luckynumbers[1] || luckynumbers[2] || luckynumbers[3] || luckynumbers[4])
{
    std::cout << "You are lucky!";
}

Anyone has any tips/better practice ways to write the if statement part?

  • 1
    That `if` statement doesn't even do what you think it does. You'll be surprised to learn that it doesn't actually check if `choice` is in the array. So, yes, there are better ways to write that. Any way that actually does it correctly would be better, of course. – Sam Varshavchik Apr 17 '21 at 15:01
  • If your container is over 1mb in size, you may want to consider using `std::binary_search`, otherwise, use a loop. – Thomas Matthews Apr 17 '21 at 17:39

2 Answers2

1

Use a for loop

int luckynumbers[5] = { 3, 5, 8, 15, 19};

std::cout << "Enter number from 1 - 20: ";
int choice;

std::cin >> choice;
for(int i = 0; i < 5; i++) { // or whatever the size of your array is
   if(choice == luckynumbers[i]) {
          std::cout << "You are lucky!";
   }
}
nwatx
  • 108
  • 1
  • 5
1

You should try using loops.

for(int i=0;i<5;i++)
{
if(luckynumber[i]==choice){
   cout<<"You're Lucky"<<endl;
}
}
Shahzaib
  • 103
  • 1
  • 11