I need to write some java using 3 "for" loops that outputs
122333444455555
22333444455555
333444455555
444455555
55555
The code I have so far:
public static void problemFour() {
for(int i = 5; i >= 1; i--) {
for(int a = 1; a <= i; a++) {
for(int b = 1; b <= a; b++) {
System.out.print(a);
}
}
System.out.println();
}
}
This outputs
111112222333445
11111222233344
111112222333
111112222
11111
I've switched around a lot of combinations of ++'s --'s, <'s, >'s, 5's, and 1's.
I'm pretty stuck, if someone could point me in the right direction, that would be fantastic.
You made mistake in how the line starts and how many times a digit (here character) gets repeated. Fix it by:
for(int i = 1; i <= 5; i++) { // Each iteration for one line
for(int a = i; a <= 5; a++) { // starts with a for ith line
for(int b = 1; b <= a; b++) { // a times `a` digit
System.out.print(a);
}
}
System.out.println();
}
To simply your problem, first think about printing this pattern :
12345
2345
345
45
5
Then extend it: in innermost loop put the code for repetition equal to digit times, using :
for(int b = 1; b <= a; b++) { // a times `a` digit
System.out.print(a);
}
We can use the observation that number 1
is printed only once, 2
twice, 3
thrice, etc.
firstValueInLine
keeps the number the line starts;
number
is the number in line being printed;
counter
just ensures that number
is printed number
times
for (int firstValueInLine = 1; firstValueInLine <= 5; ++firstValueInLine) {
for (int number = firstValueInLine; number <= 5; ++number) {
for (int counter = 0; counter < number; ++counter) {
System.out.print(number);
}
}
System.out.println();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With