If the statement to execute is (very) short, you can write it on the same line with the condition that is being checked.
Consider a program that is asking a user to answer Yes or No to a question such as "Are you ready to provide your credit card number?". A source file of such a program could look like this:
#include <iostream>
using namespace std;
int main()
{
char Answer;
// Request the availability of a credit card from the user
cout << "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') cout << "\nNow we will get your credit card information.\n";
cout << "\n";
return 0;
}
You can write the if condition and the statement on different lines; this makes your program easier to read. The above code could be written as follows:
#include <iostream>
void main()
{
char Answer;
// Request the availability of a credit card from the user
cout << "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')
cout << "\nNow we will get your credit card information.\n";
cout << "\n";
getch();
}
You can also write the statement on its own line if the statement is too long to fit on the same line with the condition.
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:
#include <iostream>
void main()
{
char Answer;
char CreditCardNumber[40];
// Request the availability of a credit card from the user
cout << "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')
{
cout << "\nNow we will continue processing the transaction.";
cout << "\nPlease enter your credit card number without spaces: ";
cin >> CreditCardNumber;
}
cout << "\n";
getch();
}
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:
#include <iostream>
void main()
{
int Number;
cout << "Enter a non zero number: ";
cin >> Number;
if(Number)
cout << "\nYou entered " << Number << endl;
cout << endl;
getch();
}
Using the Logical Not
When a driver comes to a light that he expects to be green, we saw that he would use a statement such as, "The light is green". If in fact the light is green, we saw that the statement would lead to a true result. If the light is not green, the "The light is green" statement produces a false result. This is shown in the following table:
Color | Statement | Boolean Value |
| The light is green | true |
| The light is green | false |
|
As you may realize already, in Boolean algebra, the result of performing a comparison depends on how the Condition is formulated. If the driver is approaching a light that he is expecting to display any color other than green, he would start from a statement such as "The light is not green". If the light IS NOT green, the expression "The light is not green" is true (very important). This is illustrated in the following table:
Color | Statement | Boolean Value |
| The light is green | true |
| The light is not green | true |
|
The "The light is not green" statement is expressed in Boolean algebra as “Not the light is green”. Instead of writing “Not the light is green", in C++, using the logical Not operator , you would formulate the statement as, !"The light is green". Therefore, if P means “The light is green”, you can express the negativity of P as !P. The Boolean table produced is:
Color | Statement | Boolean Value | Symbol |
| The light is green | true | P |
| The light is not green | false | !P |
|
When a statement is true, its Boolean value is equivalent to a non-zero integer such as 1. Otherwise, if a statement produces a false result, it is given a 0 value. Therefore, our table would be:
Color | Statement | Boolean Value | IntegerValue |
| The light is green | true | 1 |
| The light is not green | false | 0 |
|
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:
|
#include <iostream>
void main()
{
char Answer;
cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ";
cin >> Answer;
if( Answer == 'y' ) // First Condition
{
cout << "\nThis job involves a high level of self-control.";
cout << "\nWe will get back to you.\n";
}
if( Answer == 'n' ) // Second Condition
cout << "\nYou are hired!\n";
getch();
}
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:
#include <iostream>
void main()
{
char Answer;
cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ";
cin >> Answer;
if( Answer == 'y' ) // One answer
{
cout << "\nThis job involves a high level of self-control.";
cout << "\nWe will get back to you.\n";
}
else // Any other answer
cout << "\nYou are hired!\n";
getch();
}
The Ternary Operator (?:)
The conditional operator behaves like a simple if…else statement. Its syntax is:
Condition ? Statement1 : Statement2;
The compiler would first test the Condition. If the Condition is true, then it would executeStatement1, 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:
#include <iostream>
void main()
{
signed Num1, Num2, Max;
cout << "Enter two numbers: ";
cin >> Num1 >> Num2;
Max = (Num1 < Num2) ? Num2 : Num1;
cout << "\nThe maximum of " << Num1
<< " and " << Num2 << " is " << Max;
getch();
}
Conditional Statements: if…else if and if…else if…else
The previous conditional formula is used to execute one of two alternatives. Sometimes, your program will need to check many more than that. The syntax for such a situation is:
if(Condition1)
Statement1;
else if(Condition2)
Statement2;
An alternative syntax would add the last else as follows:
if(Condition1)
Statement1;
else if(Condition2)
Statement2;
else
Statement-n; | | | if(Condition1)
Statement1;
else if(Condition2)
Statement2;
else if(Condition3)
Statement3;
else
Statement-n; |
|
The compiler will check the first condition. If Condition1 is true, it will execute Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute 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.
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:
|
| #include <iostream>
void main()
{
char Answer;
cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ";
cin >> Answer;
if( Answer == 'y' ) // Unique Condition
{
cout << "\nThis job involves a high level of self-control.";
cout << "\nWe will get back to you.\n";
}
else if( Answer == 'n' ) // Alternative
cout << "\nYou are hired!\n";
else
cout << "\nThat's not a valid answer!\n";
getch();
}
|
|