EMC 4315

Quiz

Lab 7: Flow control

  • Question #1:
  • How do you use an if statement to print the string "Youth message" to the browser if an integer variable, $age, is between 18 and 35? If $age contains any other value, the string "Generic message" should be printed to the browser.


  • Answer:
  • $age = 20;
    $successmessage = "Youth message";
    $failedmessage = "Generic message";
    $agemax = 35;
    $agemin = 18;

    if (($agemin <= $age) && ($age <= $agemax))
    {
      echo $successmessage;
    }
    else
    {
      echo $failedmessage;
    }



  • Question #2:
  • How do you extend your code in question 1 to print the string "Child message" if the $age variable is between 1 and 17?


  • Answer:
  • $age = 2;

    $youthmessage = "Youth message";
    $genericmessage = "Generic message";
    $childmessage = "Child message";
    $agemax2 = 17;
    $agemin2 = 1;
    $agemax = 35;
    $agemin = 18;

    if (($agemin <= $age) && ($age <= $agemax))#Age Range
    {
      echo $youthmessage;
    }
    elseif (($agemin2 <= $age) && ($age <= $agemax2))#Age Range
    {
      echo $childmessage;
    }
    else
    {
      echo $genericmessage;#Out of Age Range
    }



  • Question #3:
  • How do you create a while statement that increments through and prints every odd number between 1 and 49?


  • Answer:
  • $x = 1;

    while($x < 50)
    {
      if ($x % 2 != 0)
      {
      echo "Number: $x <br>";
      }
    $x++;
    }



  • Question #4:
  • How do you convert the while statement you created in question 3 into a for statement?


  • Answer:
  • $x = 1;

    for($x = 1; $x < 50; $x++)
    {
      if ($x % 2 != 0)
      {
      echo "Number: $x <br>";
      }
    $x++;
    }





:)