Course Content
C++ Introduction
C++ Introduction
If...else Statement
The if...else
construct in programming allows your program to take different paths and manage various potential outcomes.
It consists of two essential components: a condition and the corresponding actions or consequences based on that condition.
Here's an illustration:
main
#include<iostream> int main() { int var = 13; /* If my variable equals 13, then print "OKAY", and change variable to 15 */ if (var == 13) { std::cout << "13 == 13, it is OKAY" << std::endl; var = 15; } /* New value of variable (15) doesn't equal 13, then print "NOT OKAY" */ if (var != 13) { std::cout << "15 != 13, it is NOT OKAY" << std::endl; } }
Here, we use the 2-lines comment.
There is also a handling of the "opposite" case using else
:
main
#include<iostream> int main() { int var = 200; /* If my variable equals 13, then print "OKAY" */ if (var == 13) { std::cout << "My variable equals 13, it is OKAY" << std::endl; } /* If my variable doesn`t equal 13, then print "NOT OKAY" */ else { std::cout << "My variable doesn't equal 13, it is NOT OKAY" << std::endl; } }
There can be other if...else
inside the if...else
:
main
#include<iostream> int main() { int var = 15; if (var == 15) { //then var = 15 + 200; if (var == 300) { //then std::cout << "OKAY" << std::endl; } // otherwise else { std::cout << "NOT OKAY" << std::endl; } } }
You can also use the else if
construct:
main
#include<iostream> int main() { int var = 50; if (var == 15) { std::cout << "var equals 15" << std::endl; } else if (var == 50) { std::cout << "var equals 50" << std::endl; } else if (var == 89) { std::cout << "var equals 89" << std::endl; } else if (var == 215) { std::cout << "var equals 215" << std::endl; } }
Thanks for your feedback!