Loops

Hello everyone, I am working on a class project and need help figuring out an issue. I am new to programing. When I run the program below, it does everything i want it to do, except when i want to input another number by inputing Y on the prompt. It ends the program instead of restarting. I am wondering why it is doing that and how to solve it? any help will be greatly appreciated.

The question we were provided for the project:
"Write a program that inputs a number greater than or equal to 0. The program should then count from 0 to the number inputted using a for-loop, a while-loop, and a do…while loop. If the user’s input is not greater than or equal to 0, display an error message and require the user to try again until they get it right."


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
 #include <iostream>

using namespace std;

int main(){
    
    int counter;
    int input;
    int prompt;
    
  
    do
    {
        cout << "Enter a number greater or equal to zero: ";
        cin>> input;
        cout<<endl;
        
        for(counter=0; counter <=input; counter++)
        {
            cout << counter << " ";
    
        } //for loop
        cout<<endl;
        cout<<endl;
        cout<< "would you like to try again (Y/N): "<<endl;
        cin>>prompt;
    }while(prompt=='y'||prompt=='Y'); //do loop
    
    return 0;
}
Last edited on
In line 9 you tell the compiler that the variable prompt is an integer, but in line 27 you are basing a loop on it holding the value y or Y.

Change the variable type on line 9 to char. line your code should look like this.

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
 #include <iostream>

using namespace std;

int main(){
    
    int counter;
    int input;
    char prompt;
    
  
    do
    {
        cout << "Enter a number greater or equal to zero: ";
        cin>> input;
        cout<<endl;
        
        for(counter=0; counter <=input; counter++)
        {
            cout << counter << " ";
    
        } //for loop
        cout<<endl;
        cout<<endl;
        cout<< "would you like to try again (Y/N): "<<endl;
        cin>>prompt;
    }while(prompt=='y'||prompt=='Y'); //do loop
    
    return 0;
}
oh I see. Thank you!!!!!! :)
Topic archived. No new replies allowed.