Selection Structure – The if and if/else Statement


Any simple program usually consists of lines of code that are executed one after the other unconditionally. Take the example of following simple c++ program…

int newData;
cout << “Please enter a number: “;  //Outputs text to screen
cin >> newData; // Takes user input into the specified variable
cout << “The Number You Enter is : ” << newData;

All these lines of code are executed one after the other as soon as the program runs.

There are times however, when a choice has to be made, a decision to choose between two or more code blocks. This is where the selection structures like if, if/else, and if/else if come in handy.

For example, if we modify the above program to display the number only if it is greater than 10.

int newData;
cout << “Please enter a number: “;  //Outputs text to screen
cin >> newData; // Takes user input into the specified variable
if ( newData > 0 )
{
cout << “The Number You Enter is : ” << newData;
}

The statement inside the if () is called condition or relational expression which MUST evaluate to true or false. If the result is true, the code block inside if is executed, otherwise skipped.

Let’s go through the program step by step.

  1. Variable newData is initialized
  2. Display message to user
  3. Take input from user
  4. Check if input is greater than 0
  5. If Input is greater than zero, display the message and the number
  6. Exit the program

Now let’s modify the program again to see how if/else structure works. Now we’ll enable the program to display different messages based on the input given by the user.

int newData;
cout << “Please enter a number: “;  //Outputs text to screen
cin >> newData; // Takes user input into the specified variable
if ( newData > 5 )
{
cout << “The Number: ” << newData <<” is greater than 5″;
}
else
{
cout << “The Number: ” << newData << ” is less than 5″;
}

Now if the number given by user is greater than 5, then the block inside if is executed otherwise, the block inside else is executed.

Using these control structures, a programmer is able to decide whether a certain piece of code should execute or not and also can choose between alternate choices, hence named the Selection Control Structure.

About these ads

About Ali Turab Gilani
BS Computer Sciences from G.C University Lahore. Served as Teaching Assistant for Programming Fundamentals... Vice President IEEE Society Student Chapter...

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: