While Loops
 

// To print a horizontal row of 50 asterisks:
(note various ways of accomplishing the same task)


int number = 0;
while (number < 50)
{
System.out.print( "*");
number++;
}
System.out.println("\n Here are " + number +" stars");

-----------------

int number = 1;
while (number <= 50)
{
System.out.print( "*");
number++;
}
System.out.println("\nHere are " + number+ "stars");

To print the numbers 4 - 14 on a single line:


int num = 4;
while (num < 15)
{
System.out.print( (num++) + " ");
}

int num = 4;
while (num <=14)
{
System.out.print(( num++) + " ");
}

Program quits when a -1 is entered:


(using a specified number (called a SENTINEL) to terminate a situation)
(Notice the use of TWO keyboard retrieval statements to "prime" the while loop.)
int count = 0;
int grade;

grade=Console.readInt("Please enter grade ( enter -1 to quit)");

while (grade != -1)
{
count++;
System.out.println("Grade # " + count + " is " + grade);

grade=Console.readInt("Please enter grade ( enter -1 to quit) ");
}


(c) Shilpa Sayura Foundation 2006-2017