I’m doing some programming exercises at the end of chapter four in “Introduction to Java Programming: Comprehensive Version” by Y. Daniel Liang. On question 4.18 I came up with two different solutions.
Which solution(PatternLoop1 or PatternLoop2) is more effective and why?
public class PatternLoop1 {
public static void main(String[] args) {
for (int counter = 0; counter < 6; ++counter) {
for (int counter2 = 0; counter2 <= counter; ++counter2) {
System.out.print(counter2 + 1);
}
System.out.println();
}
}
}
public class PatternLoop2 {
public static void main(String[] args) {
for (int counter = 1; counter < 7; counter++) {
for (int counter2 = 1; counter2 < 7 && counter2 <= counter; counter2++) {
System.out.print(counter2);
}
System.out.println();
}
}
}
EDIT: I hadn’t noticed the
code-efficiencytag before. The answer below is about how effective the solutions are – and the effectiveness of code includes how readable it is, IMO. (That’s how effectively it expresses its aims.) The efficiency differences will be unmeasurably small.Assuming the aim is to print 1, then 1 2, then 123 … up to 123456 I’d go with something between the two, where all the numbers are the ones involved in the output:
Note that counter is always <= 6, so we don’t need an extra check for
counter2being <= 6.Also note that most of the time we need numbers in the range [0, n) in my experience – the [1, n] requirement here is relatively rare. Of course it depends on what you’re doing, but you should think of the natural way of expressing the range. If the natural inclination is to make the upper bound inclusive, use
<=; if the natural inclination is to make the upper bound exclusive, use<.