Related Articles

# R – if-else statement

• Last Updated : 03 Aug, 2021

The if-statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the R else statement. We can use the else statement with if statement to execute a block of code when the condition is false.

Syntax:

```if (condition)
{
// Executes this block if
// condition is true
} else
{
// Executes this block if
// condition is false
}``` Working of if-else statements

1. Control falls into the if block.
2. The flow jumps to Condition.
3. Condition is tested.
1. If Condition yields true, goto Step 4.
2. If Condition yields false, goto Step 5.
4. The if-block or the body inside the if is executed.
5. The else block or the body inside the else is executed.
6. Flow exits the if-else block.

Example 1:

 `x <``-` `5``  ` `# Check value is less than or greater than 10 ``if``(x > ``10``)``{ ``    ``print``(paste(x, ``"is greater than 10"``)) ``} ``else``{ ``    ``print``(paste(x, ``"is less than 10"``)) ``}`

Output:

``` "5 is less than 10"
```

Here in the above code, Firstly, x is initialized to 5, then if-condition is checked(x > 10), and it yields false. Flow enters the else block and prints the statement “5 is less than 10”.

Example 2:

 `x <``-` `5`` ` `# Check if value is equal to 10 ``if``(x ``=``=` `10``)``{ ``    ``print``(paste(x, ``"is equal to 10"``)) ``} ``else``{ ``    ``print``(paste(x, ``"is not equal to 10"``)) ``}`

Output:

``` "5 is not equal to 10"
```

My Personal Notes arrow_drop_up