Java Reference
In-Depth Information
the bottom half. We divided the program into two parts because the number of stars keeps
increasing initially, but then it starts decreasing after the middle line. The pseudocode 1 for
our algorithm follows.
l et n be the s i ze of the diamond
nSpaces = n 1;
nStars = 1;
for every line in the first half
{
print nSpaces spaces ;
print nStars stars ;
print new line ;
increment the number of s tar s by 2;
decrement the number of spaces by 2;
nSpaces = 2;
nStars = n
2;
for every line in the second half
{
print nSpaces spaces ;
print nStars stars ;
print new line ;
decrement the number of s tar s by 2;
increment the number of spaces by 2;
}
We know how many lines are in the first and second half of the diamond. We also know
how many stars and spaces to print at every line. Therefore, we are ready to implement our
program. Note that the program will involve nested for loops. A nested for loop is a loop
inside a loop. For example, we will create one loop to iterate over the lines. Then, for every
line, we will create inner for loops to print the spaces and stars. The code of the program
follows.
1
import java . util . ;
2
3 public class Diamond
{
4
public static void main(String [] args)
{
5
Scanner keyboard = new Scanner(System. in) ;
6
System . out . p r i n t ( "Enter size of diamond: " );
7
int size = keyboard . nextInt () ;
8
int numStars = 1;
9
int numSpaces = s i ze
1;
10
for ( int line = 0; line
<
size / 2 + 1; line++)
{
11
for ( int i=0;i
<
numSpaces ;
i++)
{
12
System . out . p r i n t ( "" );
13
}
14
for ( int i=0;i < numStars ;
i++)
{
15
System . out . p r i n t ( "* " );
16
}
17
System . out . p r i n t l n ( ) ;
18
numSpaces =2;
19
numStars += 2;
20
}
21
numStars=size 2;
22
numSpaces = 2;
1 Pseudocode is a description of an algorithm that uses a language that is similar, but not identical, to
a programming language.

Search WWH ::

Custom Search