Albany Programming Course Supplement

Tracing Program Codes

while versus if

Problem:  Here are two programs.  They both print 100 lines.  The only difference between them, besides name, is that one has an if statement and the other has a while statement inside the body of the for loop. Each line consists of zero or more dots. Predict the best approximation to the average number of dots per line printed by each. In the language of probability, you are asked to calculate the expected value of the number of dots per line.

class IfDotter
{
    public static void main(String[] a)
    {
	double printDotProb = 0.75;
	for(int i=0; i < 100; i++)
	    {
		if(Math.random() <= printDotProb)
		    System.out.print(".");  //Don't go the next line yet.
		System.out.println(); //Go to the next line
		//after printing either a blank or a non-blank line.
	    }
    }
}

class WhileDotter
{
    public static void main(String[] a)
    {
	double printDotProb = 0.75;
	for(int i=0; i < 100; i++)
	    {
		while(Math.random() <= printDotProb)
		    System.out.print("."); //Don't go the next line yet.
		System.out.println(); //Go to the next line
		//after printing either a blank or a non-blank line.
	    }
    }
}
Homework problem:  Copy and modify these programs so they count the number of dots each prints and then calculate and print the average number of dots per line.  Run each modified program 10 times and report the twenty possibly different averages.


There has been error in communication with booki server. Not sure right now where is the problem.

You should refresh this page.