Home

Conditional Statements

 

Logical Operators

 

Introduction

When programming, you will ask the computer to check various kinds of situations and to act accordingly. The computer performs various comparisons of various kinds of statements. These statements come either from you or from the computer itself, while it is processing internal assignments.

Let’s imagine you are writing an employment application and one question would be, "Do you consider yourself a hot-tempered individual?" The source file of such a program would look like this:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char Answer;
	
    Console::Write("Do you consider yourself a hot-tempered individual? ");
    cin >> Answer;

    Console::WriteLine();
    return 0;
}

Some of the answers a user would type are y, yes, Y, Yes, YES, n, N, no, No, NO, I don’t know, Sometimes, Why are you asking?, and What do you mean? The variety of these different answers means that you should pay attention to how you structure your programs, you should be clear to the users.

A better version of the line that asks the question would be:

Console::Write("Do you consider yourself a hot-tempered individual? (y=Yes/n=No)";

This time, although the user can still type anything, at least you have specified the expected answers.

A program is a series of instructions that ask the computer (actually the compiler) to check some situations and to act accordingly. To check such situations, the computer spends a great deal of its time performing comparisons between values. A comparison is a Boolean operation that produces a true or a false result, depending on the values on which the comparison is performed.

A comparison is performed between two values of the same type. For example, you can compare two numbers, two characters, or the names of two cities. On the other hand, a comparison between two disparate values doesn't bear any meaning. For example, it is difficult to compare a telephone number and somebody's age, or a music category and the distance between two points. Like the binary arithmetic operations, the comparison operations are performed on two values. Unlike arithmetic operations where results are varied, a comparison produces only one of two results. The result can be a logical true or false. When a comparison is true, it has an integral value of 1 or positive; that is, a value greater than 0. If the comparison is not true, it is considered false and carries an integral value of 0.

The C++ language is equipped with various operators used to perform any type of comparison between similar values. The values could be numeric, strings, or objects (operations on objects are customized in a process referred to as Operator Overloading).

 

Equality ==

To compare two variables for equality, C++ uses the == operator. Its syntax is:

Value1 == Value2

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false or 0.
 

Equality Flowchart

Most of the comparisons performed in C++ will be applied to conditional statements; but because a comparison operation produces an integral result, the result of the comparison can be displayed on the monitor screen using a cout extractor. Here is an example:
 

#using <mscorlib.dll>
using namespace System;

int main()
{
    int Value = 15;

    Console::Write("Comparison of Value == 32 produces ");
    Console::WriteLine(Value == 32);

    Console::WriteLine();
    return 0;
}

This would produce:

Comparison of Value == 32 produces False

Press any key to continue

The result of a comparison can also be assigned to a variable. As done with the cout extractor, to store the result of a comparison, you should include the comparison operation between parentheses. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
    int Value1 = 15;
    int Value2 = (Value1 == 24);

    Console::Write("Value 1 = ");
    Console::WriteLine(Value1);
    Console::Write("Value 2 = ");
    Console::WriteLine(Value2);
	
    Console::Write("Comparison of Value1 == 15 produces ");
    Console::WriteLine(Value1 == 15);

    Console::WriteLine();
    return 0;
}

This would produce:

Value 1 = 15
Value 2 = 0
Comparison of Value1 == 15 produces True

Press any key to continue

Very important

The equality operator and the assignment operator are different. When writing StudentAge = 12, this means the constant value 12 is assigned to the variable StudentAge. The variable StudentAge can change anytime and can be assigned another value. The constant 12 can never change and is always 12. For this type of operation, the variable StudentAge is always on the left side of the assignment operator. A constant, such as 12, is always on the right side and can never be on the left side of the assignment operator. This means you can write StudentAge = 12 but never 12 = StudentAge because when writing StudentAge = 12, you are modifying the variable StudentAge from any previous value to 12. Attempting to write 12 = StudentAge means you want to modify the constant integer 12 and give it a new value which is StudentAge: you would receive an error.

NumberOfStudents1 == NumberOfStudents2 means both variables exactly mean the same thing. Whether using NumberOfStudents1  or NumberOfStudents2, the compiler considers each as meaning the other.

 

Inequality !=

As opposed to Equality, C++ provides another operator used to compare two values for inequality. This operation uses a combination of equality and logical not operators. It combines the logical not ! and a simplified == to produce !=. Its syntax is:

Value1 != Value2

The != is a binary operator (like all logical operators except the logical not, which is a unary operator) that is used to compare two values. The values can come from two variables as in Variable1 != Variable2. Upon comparing the values, if both variables hold different values, the comparison produces a true or positive value. Otherwise, the comparison renders false or a null value.
 

Inequality

Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
    int Value1 = 212;
    int Value2 = -46;
    int Value3 = (Value1 != Value2);

    Console::Write("Value1 = ");
    Console::WriteLine(Value1);
    Console::Write("Value2 = ");
    Console::WriteLine(Value2);
    Console::Write("Value3 = ");
    Console::WriteLine(Value3);
    
    Console::WriteLine();
    return 0;
}

This would produce:

Value1 = 212
Value2 = -46
Value3 = 1

Press any key to continue

The inequality is obviously the opposite of the equality.

Less Than <

To find out whether one value is lower than another, use the < operator. Its syntax is:

Value1 < Value2

The value held by Value1 is compared to that of Value2. As it would be done with other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a true or positive result.
 

Less Than

Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
    int Value1 = 15;
    bool Value2 = (Value1 < 24);

    Console::Write("Value 1 = ");
    Console::WriteLine(Value1);
    Console::Write("Value 1 < 24 = ");
    Console::WriteLine(Value2);
    
    Console::WriteLine();
    return 0;
}

This would produce:

Value 1 = 15
Value 1 < 24 = True

Press any key to continue

Less Than Or Equal To <=

The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is &#60;&#61; and its syntax is:

Value1 <= Value2

The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 hold the same value, result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.
 

Less Than Or Equal To

Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
    int Value1 = 15;
    bool Value2 = (Value1 <= 24);

    Console::Write("Value 1 = ");
    Console::WriteLine(Value1);
    Console::Write("Value 1 <= 24 = ");
    Console::WriteLine(Value2);
    
    Console::WriteLine();
    return 0;
}

This would produce the same result as above

Greater Than >

When two values of the same type are distinct, one of them is usually higher than the other. C++ provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its syntax is:

Value1 > Value2

Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value . Otherwise, the comparison renders false or null.

Greater Than
 

Greater Than Or Equal To >=

The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is:

Value1 >= Value2

A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand,, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result.

Greater Than Or Equal To

Here is a summary table of the logical operators we have studied:

Operator Meaning Example Opposite
== Equality to a == b !=
!= Not equal to 12 != 7 ==
< Less than 25 < 84 >=
<= Less than or equal to Cab <= Tab >
> Greater than 248 > 55 <=
>= Greater than or equal to Val1 >= Val2 <

 

Logical Statements

 

if a Condition is True

In C++, comparisons are made from a statement. Examples of statements are:

  • You are 12 years old
  • It is raining outside
  • You live in Sydney

One of the comparisons the compiler performs is to find out if a statement is true. If a statement is true, the compiler acts on a subsequent instruction.

The comparison using the if statement is used to check whether a condition is true or false. The syntax to use it is:

if(Condition) Statement;

If the Condition is true, then the compiler would execute the Statement. The compiler ignores anything else:

 


 

If the statement to execute is (very) short, you can write it on the same line with the condition that is being checked. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char Answer;
	
    Console::Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
    cin >> Answer;

    // Since the user is ready, let's process the credit card transaction
    if(Answer == '1') Console::Write("Now we will need your credit card number.");

    Console::WriteLine("\n");
    return 0;
}

You can write the if condition and the statement on different lines. This can make your program easier to read. The above code could be written as follows:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char Answer;
	
    Console::Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
    cin >> Answer;

    // Since the user is ready, let's process the credit card transaction
    if(Answer == '1')
	Console::Write("Now we will need your credit card number.");

    Console::WriteLine("\n");
    return 0;
}

Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket “{“ and a closing curly bracket “}”. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char Answer;
	string creditCardNumber;
	
    Console::Write("Are you ready to provide your credit card number(1=Yes/0=No)? ");
    cin >> Answer;

    // Since the user is ready, let's process the credit card transaction
    if(Answer == '1')
    {
        Console::WriteLine("Now we will need your credit card number.");
        Console::Write("Please enter your credit card number without spaces: ");
        cin >> creditCardNumber;
    }

    Console::WriteLine("\n");
    return 0;
}

If you omit the brackets, only the statement that immediately follows the condition would be executed.

When studying logical operators, we found out that if a comparison produces a true result, it in fact produces a non zero integral result. When a comparison leads to false, its result is equivalent to 0. You can use this property of logical operations and omit the comparison if or when you expect the result of the comparison to be true, that is, to bear a valid value. This is illustrated in the following program:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int number;

    Console::Write("Enter a non zero number: ");
    cin >> number;

    if(number)
        Console::WriteLine("You entered {0} ", __box(number));

    Console::WriteLine("\n");
    return 0;
}
 

The Logical Not Operator !

When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. C++ considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is:

!Value

There are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator is to check the state of a variable.

To nullify a variable, you can write the exclamation point to its left. When used like that, you can display its value using the cout extractor. You can even assign it to another variable. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
    int Value1 = 250;
    int Value2 = 32;
    int Value3 = !Value1;

    // Display the value of a variable
    Console::Write("Value1  = ");
    Console::WriteLine(Value1);
	
    // Logical Not a variable and display its value
    Console::Write("!Value2 = ");
    Console::WriteLine(!Value2);
    // Display the value of a variable that was logically "notted"
    Console::Write("Value3  = ");
    Console::WriteLine(Value3);

    Console::WriteLine();
    return 0;
}

This would produce:

Value1  = 250
!Value2 = False
Value3  = 0

Press any key to continue

When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it. This is illustrated in the following example: 

#using <mscorlib.dll>
using namespace System;

int main()
{
    int Value1 = 482;
    int Value2 = !Value1;

    Console::Write(" Value1 = ");
    Console::WriteLine(Value1);
    Console::Write(" Value2 = ");
    Console::WriteLine(Value2);
    Console::Write("!Value2 = ");
    Console::WriteLine(!Value2);
    
    Console::WriteLine();
    return 0;
}

This would produce:

Value1 = 482
 Value2 = 0
!Value2 = True

Press any key to continue
 

Otherwise: if…else

The if condition is used to check one possibility and ignore anything else. Usually, other conditions should be considered. In this case, you can use more than one if statement. For example, on a program that asks a user to answer Yes or No, although the positive answer is the most expected, it is important to offer an alternate statement in case the user provides another answer. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char answer;
	
    Console::Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
    cin >> answer;
	
    if( answer == 'y' ) // First Condition
    {
        Console::WriteLine("This job involves a high level of self-control.");
	    Console::WriteLine("We will get back to you.");
    }
    if( answer == 'n' ) // Second Condition
        Console::WriteLine("You are hired!");

    Console::WriteLine();
    return 0;
}

The problem with the above program is that the second if is not an alternative to the first, it is just another condition that the program has to check and execute after executing the first. On that program, if the user provides y as the answer to the question, the compiler would execute the content of its statement and the compiler would execute the second if condition.

You can also ask the compiler to check a condition; if that condition is true, the compiler will execute the intended statement. Otherwise, the compiler would execute alternate statement. This is performed using the syntax:

if(Condition)
    Statement1;
else
    Statement2;

 
   

The above program would better be written as:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char answer;
	
    Console::Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
    cin >> answer;
	
    if( answer == 'y' ) // One type of answer
    {
        Console::WriteLine("This job involves a high level of self-control.");
	    Console::WriteLine("We will get back to you.");
    }
	else // Any other answer
        Console::WriteLine("You are hired!");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Do you consider yourself a hot-tempered individual(y=Yes/n=No)? g
You are hired!
Press any key to continue
 

Conditional Statements: if…else if and if…else if…else

The previous conditional statement is used to execute one of two alternatives. Sometimes, your program will need to check many more conditions than that. The syntax for such a situation is:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;

The compiler checks the first condition. If Condition1 is true, then it executes Statement1. If Condition1 is false, then the compiler checks the second condition. If Condition2 is true, then it executes Statement2. When the compiler finds a Condition-n that is true, it executes its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means you can include as many conditions as you see fit using the else if statement. If after examining all the known possible conditions you still think that there might be an unexpected condition, you can use the optional single else using one of the following formulas:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else

    Statement-n;
if(Condition1)
    Statement1;
else if(
Condition2)
    Statement2;
else if(
Condition3)
    Statement3;
else

    Statement-n;

A program we previously wrote was considering that any answer other than y was negative. It would be more professional to consider a negative answer because the program anticipated one. Therefore, here is a better version of the program:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char answer;
	
    Console::Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
    cin >> answer;
	
    if( answer == 'y' ) // One type of answer
    {
        Console::WriteLine("This job involves a high level of self-control.");
	    Console::WriteLine("We will get back to you.");
    }
	else if( answer == 'n' ) // Alternative
        Console::WriteLine("You are hired!");
    else
        Console::WriteLine("That's not a valid answer!");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Do you consider yourself a hot-tempered individual(y=Yes/n=No)? h
That's not a valid answer!
Press any key to continue

The Conditional Operator (?:)

The ternary operator involves two operators and three operands. The simplest conditional operator behaves like a regular if…else statement. Its syntax is:

Condition ? Statement1 : Statement2;

The compiler would first test the Condition. If the Condition is true, then it would execute Statement1, otherwise it would execute Statement2. When you request two numbers from the user and would like to compare them, the following program would do find out which one of both numbers is higher. The comparison is performed using the conditional operator:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    signed number1, number2, maximum;
	
    Console::Write("Enter first number:  ");
    cin >> number1;
    Console::Write("Enter second number: ");
    cin >> number2;
	
    maximum = (number1 < number2) ? number2 : number1;
	
    Console::WriteLine("The maximum of {0} and {1} is {2} ",
                       __box(number1), __box(number2), __box(maximum));

    Console::WriteLine();
    return 0;
}

A more advanced conditional operator can have have the form of if...elseif...else and as many elseif as necessary in the expression. This type of statement is usually avoided because it can be confusion.

The switch Statement

When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: “{“ to “}”. The syntax of the switch statement is:

switch(Expression)
{
    case
Choice1:
        Statement1;
    case
Choice2:
        Statement2;
    case
Choice-n:
        Statement-n;
}

The expression to examine is an integer. Since an enumeration (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int number;
	
    Console::Write("Type a number between 1 and 3: ");
    cin >> number;
	
    switch (number)
    {
    case 1:
        Console::WriteLine("You typed 1");
    case 2:
        Console::WriteLine("You typed 2");
    case 3:
        Console::WriteLine("You typed 3");
    }

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Type a number between 1 and 3: 2
You typed 2
You typed 3

Press any key to continue

The program above would request a number from the user. If the user types 1, it would execute the first, the second, and the third cases. If she types 2, the program would execute the second and third cases. If she supplies 3, only the third case would be considered. If the user types any other number, no case would execute.

When establishing the possible outcomes that the switch statement should consider, at times there will be other possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:

switch(Expression)
{
    case
Choice1:
        Statement1;
    case
Choice2:
        Statement2;
    case
Choice-n:
        Statement-n;
    default:

        Other-Possibility;
}

Therefore another version of the program above would be:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int number;
	
    Console::Write("Type a number between 1 and 3: ");
    cin >> number;
	
    switch (number)
    {
    case 1:
        Console::WriteLine("You typed 1");
    case 2:
        Console::WriteLine("You typed 2");
    case 3:
        Console::WriteLine("You typed 3");
    default:
        Console::WriteLine("{0} is out of the requested range.", __box(number));
    }

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Type a number between 1 and 3: 8
8 is out of the requested range.

Press any key to continue

 

 


Previous Copyright © 2004-2010 FunctionX, Inc. Next