Home > Back-end >  How can I generate this pattern with for loops?
How can I generate this pattern with for loops?

Time:11-12

I want to make a java program that asks for a number as input data and generates the following numerical series, the series must show the amount of numbers indicated by the user, but it will only be able to print the numbers from one to ten and then descending.

Input: 7 Output: 1, 2, 3, 4, 5, 6, 7

Input: 12 Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9

Input: 22 Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2

This is what I currently am working with:

System.out.print("Input number > ");
int number = sc.nextInt();
int j = 0;
boolean ascending = true;
for(int i = 1; i <= n4; i  ){
    if(ascending){
        if(j >= 10){
            j--;
            ascending = false;
        } else {
            j  ;
        }
    } else {
        if (j <= 1){
            j  ;
            ascending = true;
        } else {
            j--;
        }
    }
    System.out.print(j   ", ");
}

CodePudding user response:

The tricky bit in your sequence is that the limits (1 and 10) are printed twice. This means that there are not two, but three delta values in the sequence: 1, then 0, then -1. The following logic should be sufficient to produce the sequence:

int numLoops = sc.next();

int delta =  1;
int currentValue = 1;
StringBuilder result = new StringBuilder();

for (int i = 0; i < numLoops; i  ) {
    result.append(Integer.toString(currentValue)   ", ");
    currentValue  = delta;

    if (currentValue >= 10) delta = (delta == 0) ? -1 : 0;
    if (currentValue <= 1 ) delta = (delta == 0) ?  1 : 0;
}
System.out.println(result.toString());

Note that a StringBuilder instance is used to assemble the output rather than a series of calls to System.out. This is more stylish.

  •  Tags:  
  • java
  • Related