C++ else if, else, and if nesting

This is Part 4. We go into detail on the “if” statement. This includes the statements else, else if, and nesting if-else statements. After these concepts are covered, we will start a new programming Project: Metric Converter. You will see how advanced if-else statements, along with floating point math and Logical Operators will be used in this program.

Remember we will program native in the Console:

#include <iostream>
using namespace std;

int main() {

    //code

    return 0;
}

File Downloads:

Metric To Standard

Contents:

  • C++ Logical Operators:
    • && in C++
    • | | in C++
    • ! in C++
  • if / else if / else / if-else nesting
    • else
    • else if
    • if-else nesting
  • Project: Metric to US Standard

C++ Logical Operators: && (AND) || (OR) ! (NOT)

Logical Operators give you more flexibility when using the “if” statement. It allows you to have one “if” statement comparing two or more conditions.

&& AND

The AND ( && ) operator can be used in a multiple conditional “if” statement. Note the parenthesis used to make each condition more clear to the programmer.

int var1=7;
int var2=11;
int var3=20;

if( (var1 < var2) && (var3 > var1) //if condition1 AND condition2 is true

    cout << "do this"; //then do the cout statement

|| OR

The OR ( || ) operator can be used in a multiple conditional “if” statement. Note the parenthesis used to make each condition more clear to the programmer.

int var1=7;
int var2=11;
int var3=20;

if( (var1 < var2) || (var1 > var3) ) //if condition1 OR condition2 is true

    cout << "do this"; //then do the cout statement

! NOT

The NOT ( ! ) operator isn’t used as much, but can still make itself useful. Note the parenthesis used to make each condition more clear to the programmer.

int var1=7;
int var2=11;
int var3=20;
bool status=false;

if( !status && (var3 > var2) ) //if status is NOT true AND condition is true

    cout << "do this"; //then do the cout statement

if / else / else if / if-else Nesting

We covered the if statement last tutorial. Now we will cover the more advanced else and else if keywords that make the “if” statement so much more powerful. Let’s recap on the if statement:

if is a conditional statement.

If the two variables inside the parenthesis of the “if” statement meet the condition, then the code following the “if” statement will execute.

Here are the basic Conditional Symbols:

== Equals

!= Does not Equal

> Greater Than

< Less Than

<= Less Than or Equals

>= Greater Than or equals

Example:

if(var > num) 

    cout << "var is greater than num";  

//if two or more statements then use curly braces 
if(var > num) 
{
    cout << "var is greater ";

    cout << "than num";
}

The else Statement

The else in an “if” statement just says (the condition in the if statement is not true, so do what follows else”).

int input1, input2;

cout << "Input the first number "; 

cin >> input1;

cout << "\nInput the second number "; 

cin >> input2;

if( (input1 + input2) < 20 )

    cout << "\nThe two numbers added is Less Than 20";

else

    cout << "\nThe two numbers added is Greater Than 20";

Start a new project or open the last one to copy and paste the above code inside the main function above return 0. Go to Debug / Start Without Debugging.

Enter 7 and 11 as the two numbers. The if statement condition (input1 + input2) < 20 is true because 7 + 11 = 17. So the code after if is executed instead of the code after else.

Stop debugging and restart. Enter 8 and 13 as the two numbers. Now the condition (input1 + input2) < 20 is not true. The code below the “if” statement is ignored and the code below else will execute instead.

The else if Statement

Start new and copy and paste the code below. The else if keywords just make it easier to combine more than one if statement.

int input1, input2;

cout << "Input the first number "; 

cin >> input1;

cout << "\nInput the second number "; 

cin >> input2;

if( (input1 + input2) == 0)

    cout << "\nEquals Zero";

else if( (input1 + input2) < 20)

    cout << "\nLess Than 20"; 

else if( (input1 + input2) > 20)

    cout << "\nGreater Than 20";

Run the program and enter 8 as the first number and then 9 for the second. The first else if statement was triggered giving the results below “Less Than 20“.

If the result equals 20, then you would need a final else statement shown below or no cout will print. Add the code below to the end of the above code.

else

    cout << "\nNone of the conditions are true";

As an example: 19 + 1 = 20, so three conditions are false, and the code below the else will execute. Now at least one of the cout statements will print.

Note : If multiple statements are below an if, else, or else if statement, then use curly braces to enclose the block of code or you will get a build error.

A build error below because you need to enclose multiple statements in curly braces.

Error above
Corrected with curly braces

if-else nesting

You can “nest” if statements inside other if statements. Be sure to enclose the nested if statements inside curly braces to avoid errors.

int a=1,b=3,c=2;
 
if(a==b) {
 
    if(c > b)
 
        cout << "c is Greater Than b";
 
    else if( (a == b) && (b != c) )
 
        cout << "a equals b and b does not equal c";
 
    else
 
        cout << "The condition was false";
}
 
else
 
    cout << "a does not equal b";

Project: Metric to US Standard

In this project you will get to use some of what you learned in this chapter. This will be a simple converter from Metric to US Standard. We will limit things to:

Centimeters to Inches

Meters to Yards

Kilometers to Miles

All we need to know is how many inches are in a centimeter:

double cm=0.3937;

How many Yards are in a Meter:

double m=1.0936;

How many Miles are in a Kilometer:

double km=0.6214;

Two more variables are needed. The input number in Metric and the character from the Menu:

double num;

char menu_char;

Let’s start coding the project:

//Project: Metric to US Standard

double cm=0.3937;
double m=1.0936;
double km=0.6214;
double num;
char menu_char;

//Menu
cout << "Press c for Centimeters to Inches\n";
cout << "Press m for Meters to Yards\n";
cout << "Press k for Kilometers to Miles\n";

Run the program here and the menu will display.

Here is where you enter the menu character. Stop, add the code and rerun the program.

//enter c, m, or k
cin >> menu_char;

if(menu_char == 'c') {

    cout << "\nType in a number in Centimeters "; 
	
    cin >> num;

    cout << "\nNumber of Inches in " << num;

    cout << " Centimeters equals " << num * cm << " Inches";
}

Enter c for centimeters to inches conversion, and 10 for the number of centimeters.

If you press “c” then the block of statements inside the curly braces will execute. The cin will ask for the number in centimeters and put that value in num. To calculate how many inches in centimeters, we use num * cm. Remember that cm = 0.3937.

The calculation is 3.937 inches.

Add the code below for the Meter to Yards conversion. Rerun the program. Enter m. When cin prompts for a number in meters, type 100. The calculation num * m = 109.36. So the number of yards in 100 meters equals 109.36 yards.

else if(menu_char == 'm') {

    cout << "\nType in a number in Meters "; 

    cin >> num;

    cout << "\nNumber of Yards in " << num;

    cout << " Meters equals " << num * m << " Yards";
}

The same thing goes for the third block, except it converts Kilometers into Miles.

else if(menu_char == 'k') {
 
    cout << "\nType in a number in Kilometers ";
 
    cin >> num;
 
    cout << "\nNumber of Miles in " << num;
 
    cout << " Kilometers equals " << num * km << " Miles";
}

Press k and 100. The number of miles in 100 kilometers equals 62.14 miles.

Let’s put an else at the end of the if block.

else

    cout << "\nError...choose c, m, or k";

The code below it will print an error on the screen if the user submits any key other than c, m, or k. Rerun the program and type “o”. Since this program is not in a loop you have to close the console and rerun it. You will learn about loops in Part 5.

The entire program to cut and paste in a Visual C++ Console Project:

#include <iostream>
using namespace std;

int main() {
    
    // Project: Metric to US Standard

    double cm=0.3937;
    double m=1.0936;
    double km=0.6214;
    double num;
    char menu_char;

    //Menu
    cout << "Press c for Centimeters to Inches\n";
    cout << "Press m for Meters to Yards\n";
    cout << "Press k for Kilometers to Miles\n";     
	
    //enter c, m, or k    
    cin >> menu_char;

    if(menu_char == 'c') {

        cout << "\nType in a number in Centimeters ";         
		
	cin >> num;

        cout << "\nNumber of Inches in " << num;

        cout << " Centimeters equals " << num * cm << " Inches"; 
    }

    else if(menu_char == 'm') {

        cout << "\nType in a number in Meters ";         
		
	cin >> num;

        cout << "\nNumber of Yards in " << num;

        cout << " Meters equals " << num * m << " Yards"; 
    }

    else if(menu_char == 'k') {

        cout << "\nType in a number in Kilometers ";         
		
	cin >> num;

        cout << "\nNumber of Miles in " << num;

        cout << " Kilometers equals " << num * km << " Miles"; 
    }

    else

        cout << "\nError...choose c, m, or k";

    return 0; 
}

You might also want to read:

Part 1 – Installing Visual Studio C++

Part 2 – The Basics of C++

Part 3 – Conditional “if” Statement

Part 4 – else if Statement in C++

Part 5 – “switch and loops”

Part 6 – Arrays & Strings

Part 7 – Pointers

Part 8 – Functions in C++

If you like this page please share with your friends.

Leave a Comment

Your email address will not be published. Required fields are marked *