Now we can move to conditional statements in C++.
Today we can learn about the conditional statements "if & if else".
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 online survey and one question would be, "whats your martial status?" The source file of such a program would look like this:
A better version of the line that asks the question would be:
Introduction to Conditional Statements
There are three entities that participate on a traffic light: the lights, the human beings who interact with the light, and the law. The road provides a platform on which these components come together.
Today we can learn about the conditional statements "if & if else".
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 online survey and one question would be, "whats your martial status?" The source file of such a program would look like this:
#include <iostream>
void main()
{
char Answer;
cout << "Whats your martial stats? ";
cin >> Answer;
getch();
}
Some of the answers a user would type are single,married,I don’t want to tell, 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.
cout<<"Whats your martial stats?(Single/Married/Don't want to tell/Other)";
This time, although the user can still type anything, at least you have specified the expected answers.
There are three entities that participate on a traffic light: the lights, the human beings who interact with the light, and the law. The road provides a platform on which these components come together.
The Traffic Light
Everything taken into consideration, a traffic light is made of three light colors: Green – Yellow/Orange – Red. When the light is green, the road is clear for moving in. The red light signals to stop and wait. A yellow light means, “Be careful, it is not safe to proceed right now. Maybe you should wait.” When it is not blinking, the yellow light usually serves as a transition period from green to red. There is no transition from red to green.
Everything taken into consideration, a traffic light is made of three light colors: Green – Yellow/Orange – Red. When the light is green, the road is clear for moving in. The red light signals to stop and wait. A yellow light means, “Be careful, it is not safe to proceed right now. Maybe you should wait.” When it is not blinking, the yellow light usually serves as a transition period from green to red. There is no transition from red to green.
The Drivers
There are two main categories of people who deal with the traffic light: the drivers and the walkers. To make our discussion a little simpler, we will consider only the driver. When the light is green, a driver can drive through. When the light is red, the driver is required to stop and wait.
There are two main categories of people who deal with the traffic light: the drivers and the walkers. To make our discussion a little simpler, we will consider only the driver. When the light is green, a driver can drive through. When the light is red, the driver is required to stop and wait.
The Law
Rules and regulations dictate that when a driver does not obey the law by stopping to a red light, he is considered to have broken the law and there is a consequence.
Rules and regulations dictate that when a driver does not obey the law by stopping to a red light, he is considered to have broken the law and there is a consequence.
The most independent of the three entities is the traffic light. It does not think, therefore it does not make mistakes. It is programmed with a timer or counter that directs it when to act, that is, when to change lights. The second entity, the driver, is a human being who can think and make decisions based on circumstances that are beyond human understanding. A driver can decide to stop at a green light or drive through a red light…
A driver who proceeds through a red light can get a ticket depending on one of two circumstances: either a police officer caught him “hand-in-the-basket” or a special camera took a picture. Worse, if an accident happens, this becomes another story.
The traffic light is sometimes equipped with a timer or counter. We will call it Timer T. It is equipped with three lights: Green, Yellow, and Red. Let’s suppose that the light stays green for 45 seconds, then its turns and stays yellow for 5 seconds, and finally it turns and stays red for 1 minute = 60 seconds. At one moment in the day, the timer is set at the beginning or is reset and the light is green: T = 0. Since the timer is working fine, it starts counting the seconds 1, 2, 3, 4, … 45. The light will stay green from T = 0 to T = 45. When the timer reaches 45, the timer is reset to 0 and starts counting from 0 until it reaches 5; meanwhile, Color = Yellow.
if a Condition is True
In C++, comparisons are made from a statement. Examples of statements are:
When a driver comes to a traffic light, the first thing he does is to examine the light's color. There are two values the driver would put together: The current light of the traffic and the desired light of the traffic.
Upon coming to the traffic light, the driver would have to compare the traffic light variable with a color he desires the traffic light to have, namely the green light (because if the light is green, then the driver can drive through). The comparison is performed by the driver making a statement such as "The light is green".
After making a statement, the driver evaluates it and compares it to what must be true.
When a driver comes to a traffic light, he would likely expect the light to be green. Therefore, if the light is green (because that is what he is expecting), the result of his examination would receive the Boolean value of TRUE. This produces the following table:
One of the comparisons the computer performs is to find out if a statement is true (in reality, programmers (like you) write these statements and the computer only follows your logic). If a statement is true, the computer 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 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
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:
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:
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:
Otherwise: if…else
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 (?:)
|
Ok readers. If you find it hard to understand please use the comment area given below.Good Night.
Thanks,
Sidh
0 comments:
Post a Comment