26
Conditional Statements
Sometimes, we need to do things based on information we have.
For these scenarios, we have the conditional statements such as if
, else
, if else
and switch case
.
The if statement enters if the condition returns true.
if(*condition is true*)
{
// Execute this code block
}
int x = 10;
int y = 5;
if(x - y == 5)
{
// Do some work
}
// More awesome work
The else
statement works only after a if
statement and it's called if the condition in the if
statement above is false
if(*condition is false*)
{
// This code block will not execute.
}
else
{
// Execute this code block
}
int x = 10;
int y = 5;
if(x - y == 10)
{
// Will not execute this code block
}
else
{
// Execute this code block
}
A good thing to notice, is that the else
statement will hit every time the if
statement is false.
If you need to check for different values, there's the if else
statement.
if(*condition is false*)
{
// Will not execute this code block
}
else if (*condition is true*)
{
// Execute this code block
}
int x = 10;
int y = 5;
if(x - y == 10)
{
// Will not execute this code
}
else if (x - y == 5)
{
// Will execute this code
}
else
{
// Will not execute this code since the condition above was met
}
The &&
means and
in programming language, which indicates that both checks must returns true.
int x = 10;
int y = 5;
if(x == 10 && y == 5)
{
// Will execute since x value is 10 and y value is 5
}
if(x == 10 && y == 4)
{
// Will not execute because the value of y is not 4
}
The ||
means or
in programming language, which indicates that at least one of the checks must returns true.
int x = 10;
int y = 5;
if(x == 10 || y == 5)
{
// Will execute since x value is 10 or y value is 5
}
if(x == 10 || y == 4)
{
// Will execute because the value of x is 10
}
The switch case
statement executes a single section from a list of candidates based on a pattern.
switch (*value to look for*)
case *scenario 1*:
// code block
break;
default:
// Will be called every time if no candidates are found.
break;
int useThis = 2;
switch (useThis)
{
case 1:
// This will not be called because we're looking for 2
break;
case 2:
// This code block will be executed.
break;
default:
// This code will be called if no candidate is found
break;
}
You can also use the same code block for different values:
int useThis = 3
switch(useThis)
{
case 1:
// Will not execute.
break;
case 2:
case 3:
// Will execute if `useThis` values is 2 or 3
break;
}
26