Conditional Statements |
|
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:
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).
#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
#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.
#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
#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
In C++, comparisons are made from a statement. Examples of statements are:
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:
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
#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
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)
// 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
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) 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:
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 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.
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) 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) 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 |
|