The If statement is used to execute a block of code when condition is true.
if(condition){ statements; }
#include <iostream> using namespace std; int main (){ int i = 15; if ( i % 3 == 0){ cout<<i<<" is divisible by 3.\n"; } return 0; }
15 is divisible by 3.
The else statement is always used with If statement. It is used to execute block of codes whenever If condition gives false result.
if(condition){ statements; } else{ statements; }
#include <iostream> using namespace std; int main (){ int i = 16; if ( i % 3 == 0){ cout<<i<<" is divisible by 3.\n"; } else{ cout<<i<<" is not divisible by 3.\n"; } return 0; }
16 is not divisible by 3.
else if statement is used to tackle multiple conditions at a time. For adding more conditions, else if statement in used. Please see the syntax.
if(condition){ statements; } else if(condition){ statements; } ... ... ... else { statements; } }
#include <iostream> using namespace std; int main (){ int i = 16; if ( i > 25){ cout<<i<<" is greater than 25.\n"; } else if(i <=25 && i >=10){ cout<<i<<" lies between 10 and 25.\n"; } else{ cout<<i<<" is less than 10.\n"; } return 0; }
16 lies between 10 and 25.