On these masteries I’m going to show you what are IF and ELSE statements in C++ and how to use them. 

If and else are used in C++ when you want something to happen inside your code ONLY when a condition is given. 

On a flow chart, IF and ELSE look like this:

Source and more information

For example, in real life, your mom may tell you: “You are ONLY going to the party IF you score more or equal than 85 on your TC1017 exam. Else, you are not going to the party.”

For the purpose of this mastery, let’s creat that exact program. We will need an IF and ELSE statement, and some cin and cout commands we learned on mastery 10.

Let’s go ahead and create our “basic program” again.

Now, let’s grab our real life example. Let’s give the program the same condition your mom gave to you. Do as follows:

  1. Create two variables that will work as your score and the permition.
  2. Write the code were the program asks the user for the score (cin)
  3. Write the condition. 
    1. IF: the input (your score) is greater or equal than 85, the program will print a message where it says that you are going to the party.
    2. ELSE,

      the program will print a message where it says that

      you are not going to the party.

Now let’s test our program. Remeber to change directory, compile and then run.

I tested every possible condition the user could input. Remember that if your program stopped, you can simply run (./a.exe) again and the program will work. You don’t need to close the terminal and open it again. 

That’s the basic use of IF…ELSE and now you know how to use it, congrats! 😀

CC BY 4.0 Masteries 15 & 16 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.