0

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;
}
4
Contributors
5
Replies
11
Views
4 Years
Discussion Span
Last Post by Tygawr
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

Edited by Ancient Dragon: n/a

0

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

0

>>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
-2
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;
	}
}
Comments
Doesn't answer the question
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.