Tuesday, December 5, 2017

Pseudocoding, Variables and Flowcharting: Flipping a Coin

A simple task like flipping a coin is a good start in pseudocoding and flow charting.

Beginning Pseudocode:

Pseudocode is just like writing out what you want your computer program to do.  A simple program (flipping a coin, for example) might look something like this:
  1. Print the title on the screen (“Heads or Tails Game”)
  2. Ask the user, “Heads or Tails?”
  3. Flip the coin (get a random number -- either 0 or 1 with 0 being heads)
  4. Tell the user what the toss was
  5. Tell the user “You win!” or “You lose!”
  6. Say “Thank you for playing!”

Now, where would you put extra instructions that asked, “Do you want to play again?”  What about adding a score counter?  What if you wanted to display a picture of a Head or Tail?  Pseudocode is really that easy.

Looking at Programming:

If we look at a more extensive example, this one is interesting because it tallies up the number of heads and tails we get out of 100 coin flips.  This code involves using a counter, a Math.random number generator (0 or 1 is the result), a counter for the results of each of the sides of the coin, and a "do while" loop.  Study the code and see if you can figure out what the code pieces are doing.

class Toss {
        public final int HEADS = 0;
        static int countH = 0;
        static int countT = 0;
        static int counter = 0;
        private static int face;

        public static void flip() {
                face = (int) (Math.random() * 2);
        }

        public String toString() {
                String faceName;
                counter++;
                if (face == HEADS) {
                        faceName = "Heads";
                        countH++;
                } else {
                        faceName = "Tails";
                        countT++;
                }
                return faceName;
        }

        public static void main(String[] args) {
                System.out.println("Outcomes:");
                do {
                        flip();
                        System.out.println(new Toss().toString());
                } while (counter < 100);
                System.out.println("Number of Tails: " + countT);
                System.out.println("Number of Heads: " + countH);
        }
}

No comments:

Post a Comment