Do while loop

I'm trying to make a do while loop so if the user enters y or Y the program repeats from the begging but if the user enters anything else the program stops


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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <iomanip>
#include <time.h>


int main(){
    
    int counttoten = 0;
    int displaynumber;
    int nines = 0, eights = 0, sevens = 0, sixes = 0, lessthansix = 0;
    char repeatkey = 'y';
    
    
    //Seed the random number
    srand (time(NULL));
    srand (0);
    
    do {
        
        //To generate and display a series of 10 random numbers
        while (counttoten != 10) {
            
            displaynumber = rand() % 50 + 50;
            
            std::cout <<  displaynumber << std::endl;
            
            counttoten++;
            
            if (displaynumber <= 100 && displaynumber >= 90) {
                nines++; }
            if (displaynumber <= 89 && displaynumber >= 80)  {
                eights++; }
            if (displaynumber <= 79 && displaynumber >= 70) {
                sevens++; }
            if (displaynumber <= 69 && displaynumber >= 60) {
                sixes++; }
            if (displaynumber <= 59 && displaynumber >= 0) {
                lessthansix++; }
            
        }
        
        std::cout << "\n90s count: " << nines << "      80s count: " << eights << "     70s count: " << sevens << "     sixs count: " << sixes << "      Less than six count: " << lessthansix << std::endl;
        
        counttoten = 0;
        
        //Code to ask if the user wants to repeat number generation
        std::cout << "Do you want to generate another set? y or n: " << std::endl;
        std::cin >> repeatkey;
        
        
        
    } while ( repeatkey == 'y' || 'Y');
    
    return 0;
}

Last edited on
while (repeatkey == 'y' || 'Y');
Whenever you have a non-boolean value in a statement that requires one (if, while, else-if, etc.), the value will be converted to a bool. A zero indicates false, otherwise it is true.

In this case, the character 'Y' is 89 in ASCII, and 89 is greater than 0. Thus resulting in the expression always executing. You have yourself an infinite loop.

To fix this, just dorepeatkey == 'y' || repeatkey == 'Y'.

Hope this helps.
Thank you, that solved it.
Topic archived. No new replies allowed.