[ Log In ]
Skip Navigation Links

Conditional Statements or If and Switch

Conditinoal statements are statements in code that respond to conditions, or decisions. An if statement is very similar to the english equivalent.

Example:
if (condition)
executed code if condition is true;
else
executed code if condition is false;
English equivalent:
if this condition is true, then do this, else if this condition is false, then do this.
if (this condition is true)
do this;
else
do this;

if the code is lengthy for the response to each condition, then code brackets are used to contain the code.

if (condition)
{
multiple code lines;
are executed;
}
else
{
multiple lines of;
code are executed;
}

The specific condition can undergo many types of condition tests. For:

equality, use ==
not equality, use !=
less than, use <
less than or equal to <=
greater than >
greater than or equal to >=

For multiple conditions must be tested, use the "and", or "or" to compare:

the and is specified as &&
the or is specified as ||

also, use () to create a precidence so the conditions are contained and are tested in the correct order. if ((condition) && (condition)) ...

The switch statement is fery similar to the if statement, but you are able to hve multiple conditions tested in a specific variable.

switch (variable)
{
case variable result :
do this;
set of;
code statements;
break;
case another variable result :
do this;
set of;
code statements;
break;
case another variable result :
do this;
set of;
code statements;
break;
default :
if no condition;
exists, run;
this code;
break;
}

Example:
switch (month)
{
case 1 :
monthString = "January";
break;
case 2 :
monthString = "February";
break;
...

default :
monthString = "not valid";
break;
}