While if
performs an action only when its condition evaluate to true
, if
/ else
allows you to specify the different actions when the condition true
and when the condition is false
.
Example:
if (a > 1)
puts("a is larger than 1");
else
puts("a is not larger than 1");
Just like the if
statement, when the block within if
or else
is consisting of only one statement, then the braces can be omitted (but doing so is not recommended as it can easily introduce problems involuntarily). However if there's more than one statement within the if
or else
block, then the braces have to be used on that particular block.
if (a > 1)
{
puts("a is larger than 1");
a--;
}
else
{
puts("a is not larger than 1");
a++;
}