In programming we will use If Statement all the time. It is decision-making statement. We can find it in most of the programming languages heavily used today.
With If Statements we will implement criteria that must be fulfilled.
In this simple example we have variable number with starting value 5.
Then with if statement we are checking if numbers is smaller then 3. If that's the case, we are printing "Number less than 3":
#include <iostream>
using namespace std;
int main() {
int number = 5;
if (number < 3) {
cout << "Number less than 3" << endl;
}
return 0;
}
There's no printing on screen at the moment because variable is 5:
Process returned 0 (0x0) execution time : 0.051 s
Press any key to continue.
That means we need to fix our source with one more if statement to cover all options:
#include <iostream>
using namespace std;
int main() {
int number = 5;
if (number < 3) {
cout << "Number less than 3" << endl;
}
if (number > 3) {
cout << "Number is bigger than 3" << endl;
}
return 0;
}
Now we have usefull result:
Number is bigger than 3
Process returned 0 (0x0) execution time : 0.049 s
Press any key to continue.
Sure, we can use not just less and greater than symbol, but we can check for numbers being equal with another If Statement:
#include <iostream>
using namespace std;
int main() {
int number = 5;
if (number < 3) {
cout << "Number less than 3" << endl;
}
if (number > 3) {
cout << "Number is bigger than 3" << endl;
}
if (number >= 5) {
cout << "Number is equal or bigger than 5" << endl;
}
return 0;
}
Result:
Number is bigger than 3
Number is equal or bigger than 5
Process returned 0 (0x0) execution time : 0.051 s
Press any key to continue.
We have 2 confirmed cases here, number is bigger than 3 and is equal as 5. That means we can have multiple if checks one after another.
No comments:
Post a Comment