Language: EN

programacion-condicional-if-else

The IF-ELSE conditional

The conditional IF-ELSE is an evolution of the simple IF, which allows us to add code to execute when the condition is false.

Colloquially, the IF-ELSE conditional means

If this happens 🡆 do this

If not 🡆 do this other

Which, put in code format, would be something like this,

if(condition)
{
	// actions to execute if condition is true
}
else
{
	// actions to execute if condition is false
}

And in the form of a flowchart, it would look something like this

programacion-if-else

Examples of IF-ELSE conditionals in different languages

Let’s see an example of the IF-ELSE conditional. In this example, let’s assume that we have to evaluate the exam grade.

  • If it is greater than 5, the student has passed 🟢
  • If it is less than 5, the student has failed 🔴

In the case of C++, C#, Java, Kotlin, or JavaScript, this IF-ELSE conditional looks like this,

if (exam_grade >= 5)
{
	// show message 'Congratulations! You passed' 🟢
}
else
{
	// show message 'Sorry, you failed' 🔴
}

In PHP, an IF conditional is identical, with the peculiarity that variables are preceded by ’$’

if ($exam_grade >= 5) 
{
    // show message 'Congratulations! You passed' 🟢
}
else 
{
   // show message 'Sorry, you failed' 🔴
}

On the other hand, Python looks like this

if exam_grade >= 5:
    # show message 'Congratulations! You passed' 🟢
else:
	# show message 'Sorry, you failed' 🔴

And in VB, which has a slightly longer syntax because it aims to have a natural language

If exam_grade >= 5 Then
	' show message 'Congratulations! You passed' 🟢
Else
	' show message 'Sorry, you failed' 🔴
End If

For a somewhat “unusual” example, in SQL a conditional looks like this

CASE
	WHEN @exam_grade >= 5 THEN 'Congratulations! You passed 🟢'
	ELSE 'Sorry, you failed 🔴'
END AS message;

In other words, the structure of an IF conditional is basically the same in most languages, beyond some peculiar syntax of each of them.

Internal operation Advanced

Internally, the program’s control flow is similar to that of the IF block. The control flow encounters a conditional jump, which evaluates a certain condition.

If the condition is true, the flow continues with the instructions in the body of the IF. If it is false, it jumps to the body of the ELSE.

programacion-if-else-saltos

In the case of the body of the IF, at the end of it there is a jump GO-TO to the end of the body of the ELSE. In the end, both reach the same point of execution.

In this way, we have created a code fork, in which some instructions are executed or others depending on the conditional jump. Finally, both come together and the program continues.