|
We will study their meaning and how to use these special statements inside the while-statement
break;
|
Effect:
|
Schematically:
|
|
|
|
input x, y;
min = min(x, y); // this is the range of the brute force search
for every value a = {min, min-1, min-2, ..., 1} do
{
if (x and y are divisible by a)
{
print a;
exit the while loop !!!
}
}
|
|
import java.util.Scanner;
public class GCD01
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int x, y, a, min = 0;
x = in.nextInt(); // Read in number
y = in.nextInt(); // Read in number
if ( x < y )
min = x;
else
min = y;
a = min;
while ( a >= 1 ) // Run a = min(x,y), min(x,y)-1, ..., 1
{
if ( x % a == 0 && y % a == 0 )
{ // a is a divisor of x and y
System.out.println(a); // Print a (because it's a common divisor)
break; // Exit while loop !!! (Only need the largest)
}
else
{
a--; // Move to the next number !!
}
}
}
}
|
How to run the program:
|
continue;
|
Effect:
|
Effect of a continue statement in a while-loop:
|
Schematically:
|
|
|
We try every number a = 1, 2, ..., n
For each number a, we check if n % a == 0.
|
Notice that the if-condition has been changed to x % a != 0, meaning: a is not a divisor of x
When a is not a divisor of x, (the then-part), we increment a (to try next number) and jump to the end of the while-loop using the continue statement.
When x % a != 0 is false, the program will print a and increment a (to try next number)
public class Continue01
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n, a;
n = in.nextInt(); // Read in number
a = 1;
while ( a <= n ) // Run a = 1, 2, ..., n
{
if ( n % a != 0 )
{ // a is NOT a divisor of n
a++;
continue; // Jump to end of while loop
}
/* ----------------------------------------------
We reach here ONLY when "n % a != 0" is FALSE
I.e.: a is a divisor of x
---------------------------------------------- */
System.out.println(a); // Print a (because it's a divisor)
a++; // Make sure we more to the next number !!
// or else: infinite loop !!!
}
}
}
|
How to run the program:
|
|