Lottery Application

Hi,
There is something wrong with my last for loop. I don't want the program to repeat "sorry, not a winner" and it keeps printing "1" as my matching number.

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
31
32
33
34
35
36
37
38
39
40
  
   int main()
   {
      srand(time(NULL));
      int lottery[5];
      int user[5];
 
      for(int i = 0; i< 5; i++)
      {
          lottery[i] = rand() % 10;
      }
  
      cout<<"Enter 5 digits between 0 to 9:" << " ";
      cout<<endl;
  
      for (int i=0; i<5; i++)
      {
          cin>> user[i];
      }
  
      cout<< " The numbers you have entered are:" << user[0]<<" " <<user[1]<<" " << user[2]<<" "<<<
     user[3]<<" "<<user[4]<<" ";
      cout<<endl;
  
  
      cout<< " The lottery numbers are: " << lottery[0]<<" "<< lottery[1]<<" "<<lottery[2]<<" "<<ll
    ottery[3]<<" "<<lottery[4];
      cout<< endl;
  
      int match = 0;
      for(int i=0; i<5; i++){
          if (user[i] == lottery[i]){
             match++;
  
              cout<< "Your matching numbers are:" <<match;
              cout<<endl;
      }
          else if (user[i] != lottery[i]){
          cout<< " Sorry not a winner";
          cout<<endl;
closed account (48T7M4Gy)
Maybe the for loop start at line 31 has something to do with it.
closed account (37oyvCM9)
get rid of the else if on line 38 and just put an if statement outside the for loop from line 31
closed account (Sw07fSEw)
Look at what the variable match actually is. What is it? I don't know, but to me, it looks like a counter that counts how many of the matching numbers between the 5 digit user and lottery number. It's printing out 1 because 1 pair of the 5 numbers match. If the numbers don't match it prints out "Sorry not a winner". Since you're iterating through it 5 times, most of the time the numbers won't match and you'll get bombarded with that message.

Instead, use your variable match to dictate the outcome. If 4 out the 5 numbers match, is the person a winner? No. The only way the person wins is if all 5 numbers match, if match equals anything less than 5, then they will have lost. Therefore, you should probably change the logic and use your match counter. Maybe invoke something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int match = 0;
for(int i=0; i<5; i++){
    if (user[i] == lottery[i]){
		if(match == 0){ // special case so "Your matching numbers"... only prints out once
			cout<< "Your matching numbers are: ";
		}
		std::cout << users[i] << " "; 
		match++;
    }
}

std::cout<< std::endl;

if(match == 5){
	std::cout << "You're a winner!\n";
}
else{
	std::cout << "Sorry you lose\n";
}



Since the values of the lottery and user numbers are stored in arrays, user[5], lottery[5], you need to output those instead of the value of your counter match.
Topic archived. No new replies allowed.