Selection Structure – The if and if/else Statement
September 8, 2010 Leave a comment
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.
- Variable newData is initialized
- Display message to user
- Take input from user
- Check if input is greater than 0
- If Input is greater than zero, display the message and the number
- 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.
Recent Comments