Browse Source

Implement Lab 6 Exercise 6 (number triangle)

I spotted a neat way of doing this before I had to head off so couldn't resist
main
Rob Hallam 1 year ago
parent
commit
fd1fd718f2
1 changed files with 34 additions and 0 deletions
  1. +34
    -0
      week1.java

+ 34
- 0
week1.java View File

@@ -250,6 +250,7 @@ class Lab6 extends Lab {
System.out.println(String.format("%n"));
new six3();
new six5();
new six6();
}

/**
@@ -286,6 +287,39 @@ class Lab6 extends Lab {
System.out.println(String.format("TODO / NOT IMPLEMENTED until we get stdin working"));
}
}
/**
* Produce a number triangle
*
* eg:
* 1
* 2 2
* 3 3 3
* 4 4 4 4
*/
class six6 extends Section {
public six6() {
super(6);
numberTriangle(8);
}
}

/**
* @param num Size of triangle
*/
public void numberTriangle(int num) {
/* Observations:
- for even-sized triangles, preceding number of spaces starts at n=rows and decrements
- for even-sized triangles even numbers have odd spaces and vice versa
*/
int spaces = num;
for (int i = 1; i <= num; i++) {
System.out.println(" ".repeat(spaces)
+ String.format("%s ", i).repeat(i)
+ " ".repeat(spaces-1)
);
spaces--;
}
}

public void writeTimesTable(int num, int limit) {
for (int i = 0; i < (limit + 1); i++) {


Loading…
Cancel
Save