Search code examples
javaloopsfor-loopnested-loops

Nested loop to produce specific output


I've just started to learn java and am attempting to produce to following output:

$££$$$££££$$$$$

My current attempt stands as followed:

for (i = 1; i < 3; i++) {
    System.out.print("$£");
    for (j = 1; j < i + 2; ++j) {
        System.out.print("$");

Having had some experience in Python, I'm struggling to get my head around the syntax of nested loops using Java. I receive the following output:

$£$$$£$$$

Solution

  • You could do something like this when you want to easily change the characters and/or amount of times they appear:

        char odd = '$';
        char even = '£';
        int amount = 6;
    
        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < i; j++) {
                System.out.print(i % 2 == 0 ? even : odd);
            }
        }
    

    Output:

    $££$$$££££$$$$$££££££