- Logic is very important in a computer program, And conditionals are the basis for logic. Lets make a program that tells us whether our number is smaller than 5, equal to ten or neither of those.
int num; cout << "Choose a number!" << endl; cin >> num; if(num < 5) { cout << "Less than 5!" << endl; } else if(num == 10) { cout << "Its 10!" << endl; } else { cout << "Its bigger than 5 and isn't 10" << endl; } - We see three new things here if(), elif() and else:
- An if statement or an else if statement runs the code in the curly braces if the contents of the brackets are true. So if(true) {} would always run. A else if statement must be proceeded by an if or another else if.
- An else statement can be after an if or an else if, It runs if all other statements return false.