0

Say I have an infinite loop, and I want to start over or terminate depending on what user inputs.

while( 1 ) // start the inifite loop
{
	printf( "Enter your number: " ); // prompt
	scanf( "%d", &operand1 ); // store user entered number into operand1
	if ( operand1 == -1 ) {
		// terminates
	} else if ( operand1 <= 0 ) {
		// repeat from top
	}
}

I know I can use break to terminate the loop or exit() to terminate the program, but I don't know how to start over the loop...and I don't wanna use goto.

Thanks in advance!

3
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by invisal
0

Say I have an infinite loop, and I want to start over or terminate depending on what user inputs.

while( 1 ) // start the inifite loop
{
	printf( "Enter your number: " ); // prompt
	scanf( "%d", &operand1 ); // store user entered number into operand1
	if ( operand1 == -1 ) {
		// terminates
	} else if ( operand1 <= 0 ) {
		// repeat from top
	}
}

I know I can use break to terminate the loop or exit() to terminate the program, but I don't know how to start over the loop...and I don't wanna use goto.

Thanks in advance!

How about changing the while loop criteria to this:

while (operand != -1)

You'd have to either initialize operand to be something other than -1 or change the loop into a DO-WHILE loop to make sure it went through the loop at least once. You could also get rid of the if-else if statement inside the loop.

That gets you out of the loop if you enter -1, without the use of goto. You can terminate the program after the loop if you like. If by "repeat from top" you mean repeat from the top of the loop, this code does that. If by "top" you mean ABOVE that, I think I'd have to see the rest of the code and where you want to go to offer anything helpful.

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.