In computer programming, we use the if statement to run a block code only when a certain condition is met.
For example, assigning grades (A, B, C) based on marks obtained by a student.
The syntax of the if statement in Go programming is:
If test_condition evaluates to
true - statements inside the body of if are executed.false - statements inside the body of if are not executed.
Output
In the above example, we have created a variable named number. Notice the condition,
Here, since the variable number is greater than 0, the condition evaluates true.
If we change the variable to a negative integer. Let's say -5.
Now, when we run the program, the output will be:
This is because the value of number is less than 0. Hence, the condition evaluates to false. And, the body of the if block is skipped.
The if statement may have an optional else block. The syntax of the if..else statement is:
If test_condition evaluates to true,
if is executedelse is skippedIf test_condition evaluates to false,
else is executedif is skipped
Output
The number is 10, so the test condition number > 0 is evaluated to be true. Hence, the statement inside the body of if is executed.
If we change the variable to a negative integer. Let's say -5.
Now if we run the program, the output will be:
Here, the test condition evaluates to false. Hence code inside the body of else is executed.
The else statement must start in the same line where the ifstatement ends.
The if...else statement is used to execute a block of code among two alternatives.
However, if you need to make a choice between more than two alternatives, then we use the else if statement.
Here,
if test_condition1 evaluates to true
code block 1 is executedcode block 2 and code block 3 are skippedif test_condition2 evaluates to true
code block 2 is executedcode block 1 and code block 3 are skippedif both test conditions evaluates to false
code block 3 is executedcode block 1 and code block 2 are skipped
Output
Here, both the test conditions number1 == number2 and number1 > number2 are false. Hence the code inside the else block is executed.
You can also use an if statement inside of an if statement. This is known as a nested if statement.
Output
If the outer condition number1 >= number2 is true
if condition number1 == number2 is checkedtrue, code inside the inner if is executedfalse, code inside the inner else is executedIf the outer condition is false, the outer else statement is executed.