I've been programming for about a week now and I'm just learning if statements now

I made a simple program that asks the user for a number input (1-4) and depending on what they input it will add/subtract/multiply/divide 2 numbers they enter after they decide what operation they want to perform.

I made an if statement that says if the number is not equal to 1, 2, 3, 4, then it gives an error message and then asks them to re enter their choice (1-4)

However I'm not sure how to redirect the program back to the start of the code after this this way it doesn't just end after the number is re-entered.

I appreciate any help, thanks keep in mind I'm a noob at this :D

also say i wanted to list several numbers in one if statement how would i do that?

If (x != 1, 2, 3, 4)

Doesn't seem to be working

also say i wanted to list several numbers in one if statement how would i do that?

If (x != 1, 2, 3, 4)

Doesn't seem to be working

&& means "and". || means "or".


Try this:

if (x != 1 && x != 2 && x != 3 && x != 4)

or this:

if (!(x == 1 || x == 2 || x == 3 || x == 4))

or try this if( x > 0 && x < 5)

For your redirecting question, you could use do...while loop:

do {
   // input your code here
} while (x < 1 && x > 5); // If the input isn't in the range of 1-4, it will process the code in the loop block again.
commented: good alternate solution +23

Invisal: line 3: x can not be both at the same time. It should have use the || operator, not && :)

commented: Thanks for point out +3

Invisal: line 3: x can not be both at the same time. It should have use the || operator, not && :)

My bad :(

I personally think a switch statement would be more viable

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.