Is it possible to loop an if-else statement? How would such a thing be coded. Basically, this code allows the user to enter a value for a month. If it's not from 0-12 it asks the user to enter a new value. How could I get that to go through the if-else again to see if it's a valid number? Also, if I wanted to say if it's less than 0 it's invalid does that need to be it's own if statement or I could I somehow combine that with something else?

#include <iostream>

using namespace std;

int main ()
{
    cout << "Please enter a numerical value of a month: ";
	int month;
	
	cin >> month;
	
	if (month<=12)
	{
		cout << "A valid month has been entered.";
	}
	
	else
	{
		cout << "That is not a valid entry. Please enter a new value. ";
		int month;
		cin >> month;
	}
	
    return 0;
}

You may need to rearrange your program a bit, removing the if-then-else statemet.

beginning of loop
    ask for user input
    if input is valid then exit the loop
    display error message
end of loop
display message that input is valid

How do I exit a loop? The program has to be an if-else statement.

By using the proper comparison in the loop statement itself, like
while (this is true)

>>display message that input is valid

Well, then just change my previous post a little

beginning of loop
    ask for user input
    if input is valid then 
       display message that input is valid
       exit the loop
    else
        display error message
end of loop
void IfElseLoopExample()
{
	int Month;
	cout << "Please enter a numerical value of a month: " << endl;
	cin >> Month;
	
	if(Month <= 12)
	{
		cout << "A valid month has been entered." << endl;
	}
	else if(Month > 12 || Month < 0)
	{
		cout << "That is not a valid entry. Please enter a new value." << endl;
		cin >> Month;
	}
}
commented: Doesn't answer the question -4
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.