The If Statement
Programs need to make decisions. Should this statement be executed or that one? Are these parameters correct and so on. This is done using the if statement. The syntax is pretty easy.if ( conditional expression )This can be extended with else.
statement;
if ( conditional expression )So if the expression is true, statement1 is executed, otherwise statement2 is executed.
statement1;
else
statement2;
Here are some examples:
if ( a==3 )Be Careful that you don't write = when you mean ==
b=a;
if ( b==0 )
{
b=1;
a += 2;
}
else
{ b=0;
a=1;
}
Can you see the problem with this code?
if (a=1)This will always set b to 9 as (a=1) is always true. It assigns a value of 1 to a instead of comparing a with 1. The corrected line should be this.
{
b =9;
}
if (a==1)This is a common mistake amongst beginners.
Conditional Operators
This is a list of the comparisons you can make.- == Equal To. if (a == b)
- < Less than. if (a < b)
- > Greater than. if (a > b)
- != Not Equal. if ( a != b)
- < Less than or equal to. if (a <= b)
- > Greater than or equal To. if (a >= b)
On the next page : Learn about the For Loop, the first of the looping statements.

