Reputation: 71
I need to write a program that prints out the following figure:
122333444455555
22333444455555
333444455555
444455555
55555
This is my code:
for (int a = 0; a <= 5; a++)
{
for (int b = 0; b < a; b++)
{
System.out.print(a);
}
}
which prints out 122333444455555
I need to triple nest my for loops, but I'm not sure where else to start. If I could get any hints/tips, that would be greatly appreciated.
Upvotes: 1
Views: 269
Reputation: 16498
Alternatively:
for(int a = 1; a <= 5; a++){
for (int b = a; b <= 5; b++) {
for (int c = 1; c <= b; c++) {
System.out.print(b);
}
}
System.out.println();
}
Upvotes: 1
Reputation: 1430
A more common solution about you issue:
Codes
private static void printStringSequence(int number) {
for (int i = 0; i < number; i++) {
StringBuilder sb = new StringBuilder();
for (int j = i; j < number; j++) {
sb.append(generateRepeateSequence(j + 1));
}
System.out.println(sb.toString());
}
}
private static String generateRepeateSequence(int number) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < number; i++) {
sb.append(number);
}
return sb.toString();
}
Test Output
printStringSequence(5);
122333444455555
22333444455555
333444455555
444455555
55555
printStringSequence(4);
1223334444
223334444
3334444
4444
Upvotes: 0
Reputation: 40034
Since you said for loops
I assume you meant at least two of them.
for (int i = 1; i <= 5; i++) {
for(int k = i; k <= 5; k++) {
System.out.print((k+"").repeat(k));
}
System.out.println();
}
Upvotes: 0
Reputation: 379
I know that you had your answer, but I have some fun doing this LOL:
public static void main(String[] args)
{
int aux = 0;
for(int i = 1; i <=5 ; i++) {
if(i == 1) {
System.out.print("1");
} else if (i ==2){
System.out.print("22");
}else if (i ==3){
System.out.print("333");
}else if (i ==4){
System.out.print("4444");
}else if (i ==5){
System.out.print("55555\n");
if(aux != 5) {
aux ++;
i = aux;
}
}
}
}
Upvotes: 0
Reputation: 201429
I think you have over thought this. I would simplify things and use a different algorithm. Initiate a String
and mutate it with one loop. Like,
String s = "122333444455555";
for (int i = 0; i < 5; i++) {
System.out.println(s);
s = s.substring(i + 1);
}
Outputs (as requested)
122333444455555
22333444455555
333444455555
444455555
55555
Upvotes: 3