Skip to content

Commit 0f22dd7

Browse files
committed
Create Power exercise
This is just part 3 of the RowsCols exercise. Thought it'd be easier for students and teachers to split the exercises.
1 parent 81e0089 commit 0f22dd7

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.codefortomorrow.intermediate.chapter10.practice;
2+
3+
/*
4+
Power
5+
6+
Fill a 5 x 4 integer array according to
7+
the following pattern:
8+
9+
4 9 16 25
10+
8 27 64 125
11+
16 81 256 625
12+
32 243 1024 3125
13+
64 729 4096 15625
14+
15+
Print the values in 5 rows of 4 elements.
16+
Use nested loops to fill the values into the array,
17+
rather than just declaring the values initially.
18+
*/
19+
20+
public class Power {
21+
public static void main(String[] args) {
22+
// write code here
23+
}
24+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.codefortomorrow.intermediate.chapter10.solutions;
2+
3+
/*
4+
Power
5+
6+
Fill a 5 x 4 integer array according to
7+
the following pattern:
8+
9+
4 9 16 25
10+
8 27 64 125
11+
16 81 256 625
12+
32 243 1024 3125
13+
64 729 4096 15625
14+
15+
Print the values in 5 rows of 4 elements.
16+
Use nested loops to fill the values into the array,
17+
rather than just declaring the values initially.
18+
*/
19+
20+
public class Power {
21+
public static void main(String[] args) {
22+
// create a 5x4 array
23+
int[][] array = new int[5][4];
24+
25+
for (int power = 2; power < 7; power++) {
26+
for (int base = 2; base < 6; base++) {
27+
// assign the correct element based on the pattern
28+
array[power - 2][base - 2] = (int) (Math.pow(base, power));
29+
30+
// print the current element
31+
System.out.print(array[power - 2][base - 2] + "\t");
32+
}
33+
System.out.println(); // move to next row
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)