We will use if.else block of code every time when we know exactly what will be last possible option that we don't need to check.
For example, if if checks are not successful there must be last possible option that will work. You will understand this much better through practical examples over time.
In general, this is basic structure of multiple check where at the end we have (under "else") direct execution because nothing else is possible:
#include <iostream>
using namespace std;
int main() {
if () {}
if () {}
if () {}
else {
}
return 0;
}
In following code first we are establishing one variable with value 2500:
int check = 2500;
Then there's check if number is greater than or equal to 5000:
if (check >= 5000) {
cout << "I am happy this month" << endl;
}
Logically, if number is NOT greater or equal to 5000 only posible option is that number MUST be smaller than 5000 so there's NO need to check any more.
In that case we will use "else" at the end of if..else block of code:
else {
cout << "Dude, I need to change this job" << endl;
}
This is full working source:
#include <iostream>
using namespace std;
int main() {
int check = 2500;
if (check >= 5000) {
cout << "I am happy this month" << endl;
}
else {
cout << "Dude, I need to change this job" << endl;
}
return 0;
}
Result:
Dude, I need to change this job
Process returned 0 (0x0) execution time : 0.045 s
Press any key to continue.
If we change initial value from to 2500 to 60000, for example, this will be result:
I am happy this month
Process returned 0 (0x0) execution time : 0.053 s
Press any key to continue.
If..Else Statement with Inputs from Keyboard
We can combine our knowledge from past tutorials into program that will take input and check things using if..else block of code:
#include <iostream>
using namespace std;
int main() {
int check;
cout << "Please, enter monthly paycheck: " << endl;
cin >> check;
if (check >= 5000) {
cout << "That's fine" << endl;
}
else {
cout << "Meh..." << endl;
}
return 0;
}
Result with input 10:
Please, enter monthly paycheck:
10
Meh...
Process returned 0 (0x0) execution time : 2.562 s
Press any key to continue.
Result with input 80000:
Please, enter monthly paycheck:
80000
That's fine
Process returned 0 (0x0) execution time : 3.855 s
Press any key to continue.
So far so good.
No comments:
Post a Comment