Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triple Nested For Loop with specific output (java)

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.

like image 279
Cuchulainn Avatar asked Mar 07 '23 22:03

Cuchulainn


2 Answers

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);
}
like image 118
Saurav Sahu Avatar answered Mar 10 '23 11:03

Saurav Sahu


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();
    }
like image 33
Adam Kotwasinski Avatar answered Mar 10 '23 10:03

Adam Kotwasinski