4.5 Solutions

  1. The println is not in the loop because of the semi-colon. It only gets executed once.
    100 10000
    1. Any value
    2. No value
    1. Endless loop
    2. Change the || to an &&
  2. It will be an endless loop because of the semi-colon after the while
    1.  
      0
      1
      4
      9
      16
      25
    2.  
      4
      5
      6
      7
      8
      
    3.  
      25
      21
      17
      13
      9
      5
      1
    4.  
      1
      2
      6
      24
      
    1. Sum of the integers from 0 to 10
    2. Number of factors of 2 in n
    3. Sum of the digits in n
  3.  
    void setup()
    {
      int n = getInt("Enter a number to test for prime");
      boolean isPrime = true;
      for (int i = 2; i < n && isPrime; i++)
        if (n % i == 0)
          isPrime= false;
      if (isPrime)
        println(n + " is a prime number.");
      else
        println(n + " is NOT a prime number.");
    } 
  4.  
    void setup()
    {
      int n = getInt("Please enter a natural integer");
      println("Divisors of " + n + " are:");
      for (int i = 1; i <= n; i++)
        if (n % i == 0)
          print(i + " ");
      println();
    } 
  1.  
    void setup()
    {
      int n = getInt("Please enter a positive integer");
      while (n > 0)
      {
        println(n % 10);
        n /= 10;
      }
    } 
  2.  
    void setup()
    {
      int n = getInt("Please enter a positive integer");
      int temp = n;
      int numDigits = 0;
      while (temp > 0)
      {
        numDigits++;
        temp /= 10;
      }
      for (int i = numDigits; i > 0; i--)
      {
        println(n/(int)Math.pow(10,i-1));
        n %= (int) (Math.pow(10,i-1));
      }
    } 
  3.  
    3
    21
    43
    215
    43
    21
  4.  
    3456
    234
    12