5. Conditional Statements

Cards (11)

  • An if statement is used to execute code when a condition or conditions are true. This creates branches in the code where different sections are executed under different conditions.
  • Print message when a value is more than 6
    if(value > 6){
      println("Hi");
    }
  • Add 2 to a variable when a value equals 800
    if(value == 800){
      variable += 2;
    }
  • Multiply a value by -1 when a value equals 0 or 500
    if(value == 0 || value == 500){
      value *= -1;
    }
  • Print a message when one value is ‘y’ and another is less than 25
    if(value1 == y && value2 < 25){
      println("hello");
    }
  • Display a different message if a value is over 400, between 300 and 400, between 100 and 300, or less than 100
    if(value > 400){
      println("your value is over 400");
    }
    else if(value >= 300 && value <400){
      println("your value is between 300 and 400");
    }
    else if(value >= 100 && value <300){
      println("your value is between 100 and 300");
    }
    else{
      println("your value is less than 100");
    }
  • Write a procedure using if statements that will animate a square moving from the top of the screen to the bottom. When the square reaches the edge of the screen, it should reverse directions.
    void setup(){
      size(800,500);
    }
    int y = 10;
    int dir = 1;
    void animate(){
    fill(0);
    square(350,y,100);
    if(y == 400 || y == 0){
      dir = dir * -1;
    }
    y = y + dir;
    }
    void draw(){
      background(255);
      animate();
    }
  • A while loop repeats code until a condition becomes false. In comparison with a for loop, a while loop runs an arbitrary number of times, while a for loop runs for a fixed number of times. For this reason, code in the body of the loop must modify the condition variable(s), otherwise the loop will run forever.
  • Runs as long as a value equals 4
    while(value == 4){
  • Stops when a value equals “quit”
    while(!value.equals (“quit”)){
  • Runs while a value is more than 100 and a value is y
    while(value1 > 100 && value2 == ‘y’){