THE IF STATEMENT


You might have seen that in previous chapters, several of the games used the if statement. This was done because conditional tests are vital to creating functional applications. In fact, it is nearly impossible to develop a program of much complexity without the aid of conditional logic. For example, in the Click Race game that you created in Chapter 2, "Navigating the Visual C++ 2005 Express Edition Environment," you set up an if statement to change the functionality of the game. The code, shown next, disabled the game's two buttons after its timer reached 30 seconds.

 if( intTimerCounter == 30 ) {   //If the timer reaches 30, disable it   button1->Enabled = false;   button2->Enabled = false; } 

In the Speed Typing game, featured in Chapter 3, "Creating an Application Interface," you used several if statements to control program flow. For example, you used five if statements to determine which text statements the game should display, as shown here:

  //Display game sentences according to level if( intcount == 0 )   txtDisplay->Text = "Once upon a time there "   "were three little pigs."; if( intCount == 1 )   txtDisplay->Text = "In days gone by times "   "were hard but the people were strong."; if( intcount == 2 )   txtDisplay->Text = "Once in awhile something "   "special happens even to the worst of people."; 

To better understand how if statements work, look at the following example:

 if it is below 70 degrees outside   then I'll dress warmly else   I'll wear shorts 

This English-like or pseudo-code outline demonstrates how a person might apply conditional logic in everyday life. The first line sets up the conditional test, which is whether it is below 70 degrees outside. The condition, expressed as it is, can only evaluate to true or false. If the tested condition turns out to be true, the actions specified by the second statement are executed. Otherwise, an alternative course of action is taken.

Hint 

Pseudo-code is a rough, English-like outline or sketch of one or more program statements. By writing what you are trying to do in pseudo-code and then translating that pseudo-code into actual program statements, you can simplify application development. The pseudo-code, in effect, becomes an initial-Level draft version of your application.

Trick 

Writing pseudo-code can speed the development of your applications by allowing you to create appropriate comments and guide the logical flow within a function.

Now that you have seen several examples of the if statement, let's look at some of the different ways you can use it.

if Statement Syntax

The if statement allows you to test two or more conditions. Based on the results, you can then alter your program's logical flow. The if statement has many optional variants, as demonstrated by the following syntax:

 if( condition is true )   perform statement; else if( condition is true )   perform statement; else   perform statement; 

Within this structure are even more variations of how the if statement can be used. These are explored in the sections that follow.

The Single-Line if Statement

The simplest form of the if statement involves a single test and the execution of a single command. The command executes only if the test condition proves true, as demonstrated here:

 Int32 intCounter = 0; if(intCounter == 0 )   MessageBox::Show("We have a match."); 

In this example, the condition being tested determines whether the value assigned to intCounter is equal to 0. If the value assigned to intCounter is equal to 0, the conditional test evaluates to true. This causes the MessageBox.Show method to execute and display a message. However, if the test proves false, the line containing the MessageBox.Show method is skipped, and the application continues on, processing any remaining programming statements.

The main advantage of the single-line if statement is that it allows you to set up one simple, clean test and to execute a single statement only if the test proves true. This allows you to keep your code clear and logically easy to understand.

Multiline if Statements

In most cases, you need to execute more than a single statement in response to a conditional test. When this is the case, you need to use the if statement in the format demonstrated here:

 if( condition is true ) {   perform statement   perform statement   ... } 

By bracketing multiple statements, you can cause multiple lines of code to be executed in response to a given condition being true. For example:

 Int32 intCounter = 0; if( intCounter == 0 ) {   intCounter += 1   MessageBox::Show("The value of intCounter has been updated." ) } 

In this example, there are too many commands to be executed by the if statement. The solution is to place braces around the lines to be executed, creating a block of code. When you use the code this way, you can place any number of statements between the opening { symbol statement and the closing } symbol. Each is executed only if the condition in parentheses evaluates to true.

The ifelse Statement

The two previous examples demonstrate how to execute one or more commands when a tested condition evaluates as true. However, if the condition proves false, the statement or statements are skipped. But what if you want to execute one or more alternate commands if the statement proves false? One option is to write a second if statement. For example, suppose that you create a small Visual C++ application, as depicted in Figure 6.5.

image from book
Figure 6.5: Validating the player age before allowing the game to be played.

In this example, the application consists of a form with a Label, a TextBox, and a Button control. The application requires the player to type an age and click on the button labeled Submit Age before continuing. The following statements show the program code that has been added to the Button control's click event:

 private: System::Void btnAge_Click(System::Object^ sender, System::EventArgs^  e) {   Double dblAge = 0;   Double::TryParse( txtAge->Text, dblAge );   if( dblAge < 18 )     MessageBox::Show( "Thanks for playing!" );   if( dblAge >= 18 )     MessageBox::Show( "Sorry, you're too old!" ); } 

As you can see, the example uses two different if statements within the btnAge function. The first if statement checks to see if the player is less than 18 years old. The second if statement checks to see if the player is 18 or older. If the player is younger than 18, a message is displayed thanking the player for playing. Otherwise, the player is told that he does not meet the age criteria for the game.

Although two if statements certainly get the job done, this example can be made even simpler. Because there are only two logical conditions, one the alternative of the other, a better way to accomplish the same result is to use an if...else statement, as demonstrated here:

 private: System::Void btnAge_Click(System::Object^ sender, System::EventArgs^  e) {   Double dblAge = 0;   Double::TryParse( txtAge->Text, dblAge );   if( dblAge < 18 )     MessageBox::Show( "Thanks for playing!" );   else     MessageBox::Show( "Sorry, you're too old!" ); } 

As you can see, the if...else version of this example is slightly smaller and requires one less conditional test, making the programming logic simpler and easier to follow.

The ifelse if Statement

If your application calls for it, you can add the else if keyword one or more times to expand the if statement. Each instance of the else if keyword allows you to test for another alternative condition. To better understand how the if...else if statement works, see the following example, shown in Figure 6.6.

image from book
Figure 6.6: Using an if...else if statement to process the contents of a ComboBox control.

In this example, a new Visual C++ application has been created, consisting of a form with a Label, a Button, and a ComboBox control.

Trick 

The ComboBox control provides a drop-down list from which the user can select a single option. After adding a ComboBox control to a form at design time, you can populate it with choices by locating its Items property in the Properties window and clicking on the (Collection) entry in the Value column. This opens the String Collection Editor, as shown in Figure 6.7. All you have to do now is enter the choices that you want to display in the ComboBox control, making sure to type each option on its own line.

image from book
Figure 6.7: Using the String Collection Editor at design time to populate the contents of a ComboBox control.

To make a selection, the user must select one of the choices displayed in the ComboBox control and then click on the form's Button control. When this occurs, the code that is assigned to this control's click event, shown in the next example, executes:

 private: System::Void btnSubmit_Click(System::Object^ sender, System::EventArgs^  e) {   if( cboAge->Text->Contains( "1 – 12" ) )     MessageBox::Show( "There is a skateboard park just"     " down the street." );   else if( cboAge->Text->Contains( "13 – 18" ) )     MessageBox::Show( "There is a 99 cent movie theater"     "2 blocks over." );   else if( cboAge->Text->Contains( "19 – 21" ) )     MessageBox::Show( "A new dance club has opened"     "downtown on 3rd Street." );   else     MessageBox::Show( "Oh, you must be ready for a"     "nap!" ); } 

As you can see, by adding multiple else if keywords, you are able to setup a logical test that can screen for multiple conditions.




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net