Search code examples
javanested-loops

Nested loop construction


This is part of my homework. All I need is a bit of advice. I need to write some nested loop constructs, to print the following:

"122333444455555"

"+**+++****+++++"

"--***++++-----******+++++++"

Here is my code to print the first set of symbols

public static void main (String[] args)
{
    int i,j;
    for(i=1;i<6;++i)
    {
        for(j=1;j<i+1;++j)
        {
            System.out.print(i);
        }
    }
}

This works perfectly fine. I'm just having trouble figuring out the second and third set of symbols.
Apologies for my lack of experience, I'm fairly new to Java.


Solution

  • public static void main(String[] args) throws IOException {
    
        int i, j;
    
        for (i = 1; i < 6; ++i) {
            for (j = 1; j < i + 1; ++j) {
                System.out.print(i);
            }
        }
    
        System.out.println();
    
        for (i = 1; i < 6; i++) {
            if (i % 2 == 1) {
                for (j = 1; j < i + 1; ++j){
                System.out.print("+");
                }
            } else {
                for (j = 1; j < i + 1; ++j){
                    System.out.print("*");
                }
            }
        }
    
        System.out.println();
    
        for (i = 2; i < 8; i++) {
            if (i % 3 == 1) {
                for (j = 1; j <= i; ++j){
                    System.out.print("+");
                }
            } else if (i % 3 == 2) {
                for (j = 1; j <= i; ++j){
                    System.out.print("-");
                }
            } else {
                for (j = 1; j <= i; ++j){
                    System.out.print("*");
                }
            }
        }
    }
    

    Cycle #1: You have to print out numbers from one to five and each number N has to be printed out N times.

    for (i = 1; i < 6; ++i) { // this would set `i` to numbers from 1-5
    
    for (j = 1; j < i + 1; ++j) { // for each cycle (next number) it prints 
    //it out N times where N is the cycle number. 1 is the first cycle,
    //2 is the second and so on.
    

    Cycle #2: Same problem but instead of printing out number of the cycle you have to print out + or * based on if the cycle number is odd or even.

    To check if the number is even you can use:

    int number = 1;
    if(number % 2 == 0){ // is true if the number is even
    

    This checks whats the remainder from the division of number by two.

    Cycle #3: Same as #2 but you start from the second cycle, not from the first and you check for the remainder after division by 3.