Conditional structure: if...else
This structure lets you run a certain block of code once only if a given condition is true. It also lets you define an alternative block of code to run once only if the condition is false. It means that you set a logic expression (bool), and if this expression results true, the first code is executed and the second (if exists) is skipped; but if the expression is false, the second code is executed and the firt one is skipped. To use this estructure, you must write the keyword if followed by the condition surrounded by parenthesis. After that goes the code to run when its true, and optionally the keyword else and the code to run when its false.
Example 1: Calculating the absolute value of n:
`int n;
cin>>n;
if (n<0) {
n=-n;
}
cout<<"Abs is: "<<n<<endl;
`
When you apply abs to a negative number (condition is true), it becames its positive opposite (n=-n). But if the number was positive (condition was false), it remains unchanged (there's no else clause).
Example 2: Finding out if a number is odd or even:
`int n;
cin>>n;
if (n%2==0) {
cout<<"The number is even."<<endl;
} else {
cout<<"The number is odd."<<endl;
}
`
The condition asks if the reminder of dividing the number by 2 is 0. The program while evaluate that condition and display only one of the two messages according to its result.