Skip to content

Commit 81e0089

Browse files
committed
Create Asterisks exercise
This is just part 2 of the RowsCols exercise. Breaking it into multiple exercises makes it more manageable.
1 parent c5dc043 commit 81e0089

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.codefortomorrow.intermediate.chapter10.practice;
2+
3+
/*
4+
Asterisks
5+
6+
Fill a 3 X 3 string array so that the values
7+
in each row are "*", "**", "***".
8+
Print the values in 3 rows of 3 elements, each separated by a tab.
9+
Fill the array with values using a loop.
10+
Keep track of the total number of asterisks in the array,
11+
and print it below the array values.
12+
*/
13+
14+
public class Asterisks {
15+
public static void main(String[] args) {
16+
// write code here
17+
}
18+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.codefortomorrow.intermediate.chapter10.solutions;
2+
3+
/*
4+
Asterisks
5+
6+
Fill a 3 X 3 string array so that the values
7+
in each row are "*", "**", "***".
8+
Print the values in 3 rows of 3 elements, each separated by a tab.
9+
Fill the array with values using a loop.
10+
Keep track of the total number of asterisks in the array,
11+
and print it below the array values.
12+
*/
13+
14+
public class Asterisks {
15+
public static void main(String[] args) {
16+
// create a 3x3 array
17+
String[][] b = new String[3][3];
18+
String asterisks = "*";
19+
int numberOfAsterisks = 0;
20+
21+
// iterate through the 3x3 array
22+
for (int row = 0; row < 3; row++) {
23+
for (int col = 0; col < 3; col++) {
24+
// store the asterisk(s) in the array
25+
b[row][col] = asterisks;
26+
27+
// print the current element
28+
System.out.print(b[row][col] + "\t");
29+
30+
// update total number of asterisks in array
31+
numberOfAsterisks += row + 1;
32+
}
33+
System.out.println(); // move to next row
34+
asterisks += "*"; // each row has 1 more asterisk than the last one
35+
}
36+
37+
// print the total number of asterisks in the array
38+
System.out.println("Number of asterisks: " + numberOfAsterisks);
39+
}
40+
}

0 commit comments

Comments
 (0)