Java Reference
In-Depth Information
26 low++;
27 high--;
28 }
29
30 if (isPalindrome)
31 System.out.println(s + " is a palindrome" );
32 else
33 System.out.println(s + " is not a palindrome" );
34 }
35 }
update indices
Enter a string: noon
noon is a palindrome
Enter a string: moon
moon is not a palindrome
The program uses two variables, low and high , to denote the position of the two charac-
ters at the beginning and the end in a string s (lines 14, 17). Initially, low is 0 and high is s.
length() - 1 . If the two characters at these positions match, increment low by 1 and decre-
ment high by 1 (lines 26-27). This process continues until ( low >= high ) or a mismatch
is found (line 21).
The program uses a boolean variable isPalindrome to denote whether the string s is pal-
indrome. Initially, it is set to true (line 19). When a mismatch is discovered (line 21), isPal-
indrome is to false (line 22) and the loop is terminated with a break statement (line 23).
5.11 Case Study: Displaying Prime Numbers
This section presents a program that displays the first fifty prime numbers in five lines,
each containing ten numbers.
Key
Point
An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2 , 3 ,
5 , and 7 are prime numbers, but 4 , 6 , 8 , and 9 are not.
The problem is to display the first 50 prime numbers in five lines, each of which contains
ten numbers. The problem can be broken into the following tasks:
Determine whether a given number is prime.
For number = 2 , 3 , 4 , 5 , 6 , . . ., test whether it is prime.
Count the prime numbers.
Display each prime number, and display ten numbers per line.
Obviously, you need to write a loop and repeatedly test whether a new number is prime.
If the number is prime, increase the count by 1 . The count is 0 initially. When it reaches 50 ,
the loop terminates.
Here is the algorithm for the problem:
Set the number of prime numbers to be printed as
a constant NUMBER_OF_PRIMES;
Use count to track the number of prime numbers and
set an initial count to 0;
Set an initial number to 2;
 
 
 
Search WWH ::




Custom Search