Wednesday, March 28, 2007

Heads or Tails

Program

public class CoinFlipping {
    public static void main(String[] args) {
        int heads = 0;
        int tails = 0;
        
        for (int i = 0; i < 10; i++) {
            int number = (int) (Math.random() * 2);
            
            if (number == 0) {
                heads++;
                System.out.print("Head, ");
                
            } else { // number == 1
                tails++;
                System.out.print("Tail, ");
            }
        }
        
        System.out.println();
        System.out.println("Heads: " + heads);
        System.out.println("Tails: " + tails);      
        System.out.println("Count: " + (heads + tails));      
    }
}

Output

Tail, Head, Tail, Tail, Head, Head, Tail, Tail, Head, Tail, 
Heads: 4
Tails: 6
Count: 10

1 comment:

Fred said...

Ah, the classic coin flip program. Who didn't make something like this when they were starting out with programming? Just looking at it sure does bring back memories of my high school programming class :)