Member Avatar for woozyking

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!

Recommended Answers

All 2 Replies

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.

I am not sure what you're looking for, maybe you mean continue; ?

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.