SWEN20003
Object Oriented Software Development
Workshop 1 (Solutions)
Semester 1, 2021
Problems
1. Write a program to print a triangle of some constant size. For example, a triangle of size 5 should look
like this:
#
##
###
####
#####
Solution:
public class Program {
public static void main(String[] args) {
int N = 5;
for (int i = 1; i <= N; ++i) { for (int j = 0; j < i; ++j) { System.out.print("#"); } System.out.println(); } } } 2. Write a program to print a diamond of some constant odd size. For example, a diamond of size 5 should look like this: # ### ##### ### # Solution: public class Program { public static void main(String[] args) { int N = 5; for (int i = 1; i <= N; i += 2) { int numSpaces = (N - i) / 2; for (int j = 0; j < numSpaces; ++j) { 1 System.out.print(" "); } for (int j = 0; j < i; ++j) { System.out.print("#"); } System.out.println(); } for (int i = N - 2; i >= 1; i -= 2) {
int numSpaces = (N – i) / 2;
for (int j = 0; j < numSpaces; ++j) { System.out.print(" "); } for (int j = 0; j < i; ++j) { System.out.print("#"); } System.out.println(); } } } 2