Loops with if statement

Hello.
I'm making a program that asks user to input a day from 1 to 31 (as max day is 31), so when user enters day that is higher than 31 the program will ask to enter the day again until the input is correct. So any day from 1 to 31 should be correct input and break the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int day;
    cout<<"What is the day?"<<endl;
    cin>>day;
    if(day>0 && day<32){
       cout<<"Today is: "<<day<<endl; }
    else {
       cout<<"Incorrect day, try again."<<endl; }

return 0;
}


I don't know how to add a loop (and which loop) to this program, so it would ask the day as many times as it needs to user input correct day.
Thank you in advance.
You could use do-while loop.

1
2
3
4
5
6
7
int main() {

    do {
        //All code here what you want to be in loop.
    } while(day < 1 && day > 31);

}
Last edited on
I made it like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
    int day;
 do{
    cout<<"What is the day?"<<endl;
    cin>>day;
    if(day>0 && day<32){
       cout<<"Today is: "<<day<<endl; }
    else {
       cout<<"Incorrect day, try again.\n"<<endl; }
 }while(day>=32);
return 0;
}

And it works, thank you.
Is there any ways to do the same with while or for loops?
No problem.

With while it would be like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
    int day = 0;
    while(day < 1 || day > 31) {
        std::cout << "What is the day?" << std::endl;
        std::cin >> day;
        
        if(day > 0 && day < 32) {
            std::cout << "Today is: " << day << std::endl; 
        break;
        }

        std::cout << "Incorrect day, try again.\n" << std::endl; 
    }
 
return 0;
}
Last edited on
Ok, I think I understand it now. Thanks again
Topic archived. No new replies allowed.