Aan de slagGa gratis aan de slag

Can you If inside an If?

Sometimes it makes sense to have nested if statements to add even more control. In the following exercise, you will add an if statement that checks if you are holding a share of the Microsoft stock before you attempt to sell it.

Here is the structure of nested if statements, it should look somewhat familiar:

if(condition1) {        
    if(condition2) {     
        code if both pass
    } else {            
        code if 1 passes, 2 fails
    }
} else {            
    code if 1 fails
}

The variables, micr and shares, have been created for you.

Deze oefening maakt deel uit van de cursus

Intermediate R for Finance

Cursus bekijken

Oefeninstructies

  • Fill in the nested if statement to check if shares is greater than or equal to 1 before you decide to sell.
  • If this is true, then print "Sell!".
  • Else, print "Not enough shares to sell!".

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

micr <- 105.67
shares <- 1

# Fill in the blanks
if( micr < 55 ) {
    print("Buy!")
} else if( micr >= 55 & micr < 75 ) {
    print("Do nothing!")
} else { 
    if( ___ ) {
        ___
    } else {
        ___
    }
}
Code bewerken en uitvoeren