The if...else Statement
The if...else Statement:
The if statement lets you do something if a condition is true. If it isn’t true, nothing happens. But suppose we want to do one thing if a condition is true, and do something else if it’s false. That’s where the if...else statement comes in. It consists of an if statement, followed by a statement or block of statements, followed by the keyword else, followed by another statement or block of statements.There are many programming situations in which you must choose between two alternatives. For example, if a part-time employee works overtime, the paycheck is calculated using the overtime payment formula; otherwise, the paycheck is calculated using the regular formula. This is an example of two-way selection. To choose between two alternatives—that is, to implement if. . . else statement. if...else selection uses the following syntax:
if(expression)
{
statement-1
}
else {
statement-2
}
Here’s a variation of our IF example, with an else added to the if:
// demonstrates IF...ELSE statememt
#include <iostream>
using namespace std;
int main()
{
int x;
cout << “\nEnter a number: “;
cin >> x;
if( x > 100 )
cout << “That number is greater than 100\n”;
else
cout << “That number is not greater than 100\n”;
return 0;
}
Here’s output from two different invocations of the program:
Enter a number: 300
That number is greater than 100
Enter a number: 3
That number is not greater than 100
Click here to download source code....
Subscribe our channel now...
Comments
Post a Comment