C++ Part 4 – else if / else / if nesting

We go into detail on the “if” statement. This includes the statements else, else if, and nesting if-elsestatements. 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>

usingnamespace 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

Examples:


if(var > num) cout << "var is greater than num";

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 than num";

	cout << "var is greater than num";

}

else

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";

Go to Debug / Start Debugging.

Enter 7 and 11 as the two numbers. The if statement condition (input1 + input2) < 20 istrue because 7 + 11 = 17. So the code after if does not execute.

 

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.

else if

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";

You can add an else keyword so that at least one of the cout statements execute:


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";

else

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

In this case 19 + 1 = 20, so the three conditions are false, and the code below the else will execute.

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 syntax error.

A syntax error on the left because you need to enclose multiple statements in 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 syntax errors


int input_pause;

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 and rerun the progam.


//enter c, m, or k

cin >> menu_char;

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

Now for the first if block. 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.


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";

}

The calculation is 3.937 inches.

 

Use an else to add another if statement. Rerun the program. Enter m for Meters to Yards. Whencin 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 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";

	cout << "\n\npause...press a key then Enter... or close console window";

	cin >> input_pause;

 

The code below it will print an error on the screen if the user submits any key other than c, m, ork. Rerun the program and type o.

 

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


#include <iostream>

using namespace std;

int main() {

    int input_pause;

    // 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";

        cout << "\n\npause...press a key then Enter... or close console window";

        cin >> input_pause; 

    return 0; 

}

 

You might also want to read:

C++ for Beginners Part 8 – Functions

C++ for Beginners Part 7 – Pointers

C++ for beginners Part 6 – Arrays & Strings

C++ for beginners Part 5 – “switch and loops”

C++ for beginners Part 4 – else if Statement in C++

C++ for beginners Part 3 – Conditional “if” Statement

C++ for beginners Part 2 – The Basics of C++

C++ for beginners Part 1 – Installing Visual C++ Express

 

More C / C++ and Dev Programming Tutorials:

 

If you like this page please share with your friends:

Leave a Reply

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