Zebra0.com

cpp ifelseIntroduction to C++ Programming

Introduction to C++ Programming

Learn C++ in step-by-step lessons.

Control structure: if / else

The if statement is used to execute a statement, or group of statements only under certain conditions.

There are several possible formats:

To execute just one statement when the Boolean expression is true:

if(boolean expression) statement;

To execute one or more statements when the Boolean expression is true use { and } around the statements:

if(boolean expression) {
  statement;
  statement;
  ...
}

There is an optional else that can be used when the Boolean expression is false:

if(boolean expression) statement;
else statement;

To execute one or more statements when the Boolean expression is either true or false use { and } around the statements:

if(boolean expression) {
  statement;
  statement;
  ...
}
else {
  statement;
  statement;
  ...
}

It is usually a good idea to put each statement on a separate line, but you can write if/else on one line:

if(grade<65) cout<<"fail"; else cout<<"pass";

Please study the material at each of the links below.

  1. The syntax

  2. Not for negation

  3. Use ==, not =

  4. Swap variables to put in order

  5. Calculate tip based on service

  6. Find a letter grade

  7. Using nested if/else to find letter grade

  8. Use a variable for grade

  9. Test if a number is a valid month

  10. Who gets a discount?

  11. Print season based on month

GlossaryGlossary for ifelse lesson
Full Glossary