Loops Solutions

From CompSciWiki
Jump to: navigation, search

Main_Page > Loops


Introduction

These are the solutions for the review questions for loops.





Overview

If you did not answer any of these questions successfully make sure to go back and re-read the material. If you have trouble understanding the material talk to your prof or a TA These solutions can be compiled and run as is.

Template loop detected: Template loop detected:


Review Questions

While Loops

  1. You use a while loop when you don't know beforehand how many times you need to iterate.
  2. A while loop will continue to iterate for as long as the test condition evaluates to true.


For Loops

  1. You use a for loop if you know beforehand how many times you need to iterate.
  2. It will iterate 10 times, when 'i' = 0,5,10,15,20,25,30,35,40,45
  3. You are allowed to read the control variable in the body of the loop, but don't try to write it.


Additional Information

  1. A sentinel value is used as an abnormal end case to a loop. It is used by giving the sentinel value a value outside the operating parameters of the loop. Such as -1 if we are counting from 1 to 10. The counter is used and set to -1 so that the loop will exit before completing all of it's iterations.
  2. A running total is a count of either iterations or items. This can be used to count the sum or the number of even numbers between 1 and 20. It is used by creating a variable that will increment each time a condition is met inside the loop.
  3. Having multiple control statements or conditions in a loop is beneficial as it can increase efficiency. This is done by exiting using these extra conditions to set conditions where the loop will exit before completing all of its iterations. This can be done using a sentinel value to cause an end case that will set the result of the condition statements to be false.


Excercises

The Rock Pile

The following code is an example solution to 'The Rock Pile' game.


import javax.swing.JOptionPane;

public class TheRockPile {

	public static void main(String args[])
	{
		int numberOfRocks = 0;
		boolean userTurn = true;
		boolean numberOfRocksIsValid = false;
		int rocksToThrow = 0;
		
		// This code gets the number of rocks to start with from the user
		// and makes sure that it is valid.
		while(!numberOfRocksIsValid)
		{
			numberOfRocks = Integer.parseInt(JOptionPane.showInputDialog("Enter Number of Rocks: "));
			
			if (numberOfRocks <= 99 && numberOfRocks >= 50)
			{
				numberOfRocksIsValid = true;
				System.out.println("Number of Rocks Accepted!");
			}
			else
			{
				System.out.println("Number of Rocks is Invalid please re-enter!");
			}
		}

		
		while(numberOfRocks > 0)
		{
			
			System.out.println("Number of Rocks Remaining: " + numberOfRocks);
			
			if (userTurn)
			{
				rocksToThrow = Integer.parseInt(JOptionPane.showInputDialog("Please Enter Number of Rocks Between 1 to 3: "));
				
				while(rocksToThrow > 3 || rocksToThrow < 1 || rocksToThrow > numberOfRocks)
				{
					System.out.println("Invalid Number. Please Try Again!");
					rocksToThrow = Integer.parseInt(JOptionPane.showInputDialog("Please Enter Number of Rocks Between 1 to 3: "));
				}
				
				System.out.println("User Takes " + rocksToThrow + " rocks!");
				numberOfRocks -= rocksToThrow;
				userTurn = false;
			}
			else
			{
				if (numberOfRocks < 3)
				{
					System.out.println("Computer Takes " + numberOfRocks + " rocks!");
					numberOfRocks = 0;
				}
				else
				{
					numberOfRocks -= (4 - rocksToThrow);
					System.out.println("Computer Takes " + (4 - rocksToThrow) + " rocks!");
				}

				userTurn = true;
			}
		}
		
		if (userTurn)
                {
			System.out.println("You win!");
		}
		else
		{
			System.out.println("Sorry, you lose!");
		}
	}

}


Ascii Art X

/**********************************
* NestedX:
* Prints out a fancy "ascii art"
* picture in the shape of an X where
* the user supplies the size of the X.
***********************************/

import javax.swing.*;

public class NestedX
{
	public static void main(String[] args)
	{
		int size = 0;
		int i, j;

		// Keep asking for input until it is greater or equal to 3.
		while(size < 3)
		{
			size = Integer.parseInt(JOptionPane.showInputDialog("Enter a number greater or equal to 3"));
		}

		for(i = 0; i < size; i++)
		{
			for (j = 0; j < size; j++)
			{
				if(i == j)
				{
					System.out.print("*");
				}
				else if(j == (size - (i + 1)))
				{
					System.out.print("*");
				}
				else
				{
					System.out.print(" ");
				}
			}
			System.out.println();
		}

		System.out.println("\n~~~End of processing~~~");
		System.exit(0);

	}// end main
}// end NestedX


Guess My Number

import javax.swing.JOptionPane;

public class GuessNumber
{
  public static void main(String args[])
  {
    int myNumber = 29;
    String number;
    int guess;
    //<--Min and max variables go here-->
    int min = 1, max = 100;

    //get guess from user
    number = JOptionPane.showInputDialog("Pick a number between "+ min + " and " + max); //<--Show user min and max-->

    //convert number from string to integer
    guess = Integer.parseInt(number);
    while(guess != myNumber)
    {
      //<--Modify min or max variables here-->
      if(guess < myNumber)
      {
	min = guess;
	number = JOptionPane.showInputDialog("Too low, please pick a number between "+ min + " and " + max); //<--Show user min and max-->
      }
      else
      {
      	max = guess;
      	number = JOptionPane.showInputDialog("Too high, please pick a number between "+ min + " and " + max); //<--Show user min and max-->
      }

      //convert number from string to integer
      guess = Integer.parseInt(number);
    }
    JOptionPane.showMessageDialog(null, "Congratulations, you picked the right number");
  }
}


Pick Up Stones

import javax.swing.JOptionPane;

public class Stones
{
  public static void main(String args[])
  {
    int totalStones = 21;

    String number;
    int removed;

    //<--Uncomment when doing assignment-->
    JOptionPane.showMessageDialog(null, "Pick up 1-3 stones until all are gone");

    //get guess from user
    number = JOptionPane.showInputDialog("There are " + totalStones + " stones, pick up how many?");

    //convert number from string to integer
    removed= Integer.parseInt(number);

    //<--Ask the user for another input while removed > 3 or removed <= 0 or removed > totalStones-->
    while(removed > 3 || removed <= 0 || removed > totalStones)
    {
      //get guess from user
      number = JOptionPane.showInputDialog("Can't do that - there are " + totalStones + " stones, pick up how many?");

      //convert number from string to integer
      removed= Integer.parseInt(number);
    }

    //remove stones from pile
    totalStones -= removed;

    while(totalStones > 0) {
      number = JOptionPane.showInputDialog("There are " + totalStones + " stones, pick up how many?");

      //convert number from string to integer
      removed= Integer.parseInt(number);

      //<--Ask the user for another input while removed > 3 or removed <= 0 or removed > totalStones-->
      while(removed > 3 || removed <= 0 || removed > totalStones)
      {
        //get guess from user
        number = JOptionPane.showInputDialog("Can't do that - there are " + totalStones + " stones, pick up how many?");

        //convert number from string to integer
        removed= Integer.parseInt(number);
      }

      //remove stones from pile
      totalStones -= removed;
    }
    JOptionPane.showMessageDialog(null, "All the stones are gone");
  }
}


Division



/***********************************************************************************
* Division:
* Takes two integer numbers as input from user
* and computes the division of the first input by the second
* for this program, we accept only divisors smaller or equal to the dividing number
************************************************************************************/

import javax.swing.*;


public class Division {

		public static void main(String[] args) {
		
                /**** if we have A/B, A is the dividend and B is the divisor ****/
		int dividend;
		int divisor;
		int count = 0;
		int i ;

		dividend = Integer.parseInt(JOptionPane.showInputDialog("Enter a number to divide"));
		divisor = Integer.parseInt(JOptionPane.showInputDialog("Enter the divisor")); //gives an error if 0 or if greater than dividend
		
		while(divisor == 0){
			JOptionPane.showMessageDialog(null,"Cannot divide by zero.", "Error",JOptionPane.ERROR_MESSAGE);
			divisor = Integer.parseInt(JOptionPane.showInputDialog("Enter the divisor"));
		}
		while(divisor > dividend){
			JOptionPane.showMessageDialog(null,"Please enter a number less than " + dividend, "Error",JOptionPane.ERROR_MESSAGE);
			divisor = Integer.parseInt(JOptionPane.showInputDialog("Enter the divisor"));
		}
		
		//computes the division
		i = dividend - divisor;
		count = count+1;
		
		while(i >= 1 && i >= divisor){
			i = i - divisor;
			count = count+1;
		}
		
		//Outputs the result
		if(i > 1)
			JOptionPane.showMessageDialog(null, dividend + " divided by " + divisor + " is " + count + " remaining " + i , "Result",JOptionPane.INFORMATION_MESSAGE);
		else	
			JOptionPane.showMessageDialog(null, dividend + " divided by " + divisor + " is " + count, "Result",JOptionPane.INFORMATION_MESSAGE);
		
	}

}