This is my code which determines it a lottery number is a winner or a loser. I have specific numbers that it needs to go by. My code compiles and it congratulates the user if when I type any of the numbers, however, if I type in 12345 or several other numbers it also congratulates the user. If anyone can help me with this I would greatly appreciate it.

//This program uses a binary search and allows a lottery ticket buyer who purchases 10 tickets a week
//to enter 5 numbers to determine if he or she's number's is a winner or loser.
#include<iostream>
using namespace std;

int main()
{
   int winningNumbers[]={13579,26791,26792,33445,55555,62483,77777, 79422,85647, 93121}; //"Lucky" lottery numbers
   int numbers; //To hold lottery numbers
   int last=10, //To hold the last array element
	   first=0, //To hold the first array element
	   middle;  //To hold the midpoint of the search
   
   do
     {
      cout<<"Enter 5 numbers and I will tell you if you won: "; //Allows user to enter 5 numbers
      cin>> numbers;
      
	  if(numbers<00000||numbers>100000)
         //Input Validation, lets user know the did not put in enough or too many numbers
          cout<<"Input Validation: You need to put in 5 numbers.\n";
      }
	 while (numbers<00000||numbers>100000); //Used to determine if correct numbers were used

last--;
while (first<=last)
    {
		middle=(first+last)/2;
		
		if(winningNumbers[middle]<numbers)
			first = middle + 1;
		
		else
        {
			if( winningNumbers[middle]>numbers)
				last = middle - 1;

			else
           {
			   last=-1;
             }
        }
     }

if(last<0)

    cout<<"Congratulations, those are the winning numbers!\n"; //Lets the user know the numbers are winners
else
     cout<<"Sorry, those are not the winning numbers.\n"; //Lets user know the numbers are not winners

return 0;
}

Recommended Answers

All 2 Replies

The one problem that I can see is the if you enter a number that is smaller than the first winning number, the search will drive the middle index to 0. And if the 0th value is still bigger than the number entered, "last" will be set to middle-1 which becomes -1. So, a simple fix is to make the winning condition that you have as "last = -1;" to "last = -2" instead and check at the end "if(last < -1)". That should solve it I think.

Thank you so much Mike! That solved the problem. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.