Conditionals


Conditional statements let the program perform some code only if certain conditions are met.

To perform code under some condition we use the if statement. This is written as if followed by some condition in parentheses, followed by the code to execute in curly brackets. An if statement can be followed by an optional else statement, followed by other statements in curly brackets. The code in these brackets will be performed in the case the conditional is false.

We can test for multiple conditions using the logical operators || for or, and && for and.

Inside a conditional statement’s parentheses any value that is not 0 will evaluate to true. This is important to remember as many conditions use this to check things implicitly.

If we wished to check if an int called x was greater than 10 and less than 100, we would write the following.

  1. if (x > 10 && x < 100) {
  2. puts("x is greater than 10 and less than 100!");
  3. } else {
  4. puts("x is less than 11 or greater than 99!");
  5. }