1

How do I stop the loop if the number reaches the n? i tried the break; but the loop still doesn't stop.

Scanner in = new Scanner(System.in);

int i, j;
int n = in.nextInt();
int number = 1;

 for(i = 1; i <= n; ++i) {

  for(j = 1; j <= i; ++j) {

    System.out.print(number);
    ++number;

      if(number >= n){
        break;
      }
   }

  System.out.println();

}

input: 9

expected output:

1
23
456
789

or

input: 12

expected output:

1
23
456
78910
1112
Johny
  • 55
  • 11
  • 1
    Declare a boolean in the outer loop, set it to true before breaking the inner loop; after the inner loop ends check the boolean value: if true `break` again. – Federico klez Culloca Nov 18 '20 at 14:18
  • 2
    You have two for loops there, the break only breaks the INNER one. If you want to break the outer loop, you would need to use a *label* on that loop. – GhostCat Nov 18 '20 at 14:23
  • Like: https://stackoverflow.com/questions/3821827/loop-in-java-code-what-is-this-and-why-does-it-compile – GhostCat Nov 18 '20 at 14:23

5 Answers5

3

Use the labeled break statement and you can break from the nested loop:

loop:
for (int i = 1; i <= n; ++i)
{
    for (int j = 1; j <= i; ++j)
    {
        System.out.print(number);
        ++number;

        if (number > n) //not (number >= n)
        {
            break loop;
        }
    }

    System.out.println();
}
Jess R
  • 3
  • 3
Kapitany
  • 1,319
  • 1
  • 6
  • 10
3

Break and Labeled break should be avoided in code. So you can use loops as below:

public static void main(final String[] args) {
    Scanner in = new Scanner(System.in);

    System.out.println("Please enter input number:");

    int n = in.nextInt();

    System.out.println("You have entered : " + n);


    for (int i = 1, k = 1; k <= n; i++) {

      for (int j = 0; j < i && k <= n; j++, k++) {
        System.out.print(k);
      }
      System.out.println();
    }

  }
  1. Printing k variable which is initialized in outer and updated in inner loop.
  2. Putting condition to break inner and outer loop to check k with input variable

EDITED : To understand it better:

  1. i variable is used to maintain the number of rows we need to print.
  2. j variable is used to maintain the number to elements to print in each row.
  3. In most of placed the value which is being print is in context with either row number or element number in row, but here print value is not in sync with it, so we are maintaining it in 2rd variable k.
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
  • what is that ```final``` ? – Johny Nov 18 '20 at 14:40
  • As the input variable is not updated you can mark that field as final. But that is optional, you can avoid that. Removed that from code, as that is optional. – Gaurav Jeswani Nov 18 '20 at 14:40
  • if it's ok with you can you please explain the code? I'm confuse why there are two initialized variable in the first loop? – Johny Nov 18 '20 at 14:50
  • reference to "break and labelled break should be avoided" needed. They are included in many languages for a good reason. Yes, they should not be used always - but sometimes they are the right tool. Outright banning of language features is not good engineering. – tucuxi Nov 18 '20 at 14:51
  • @tucuxi Yes definitely it is right at some places. As this is less readable and prone to more errors. If we have a better way to do work without it. In my experience better to go with without that. – Gaurav Jeswani Nov 18 '20 at 14:53
  • @Johny Added more details, please do let me know if it is helpful to you. – Gaurav Jeswani Nov 18 '20 at 14:56
1

There are many ways of doing this. The most straightforward one is to use a label to break out of several loops at once:

 outer: for(i = 1; i <= n; ++i) {    // a label is a word followed by :

  inner: for(j = 1; j <= i; ++j) {   // you can declare labels without using them

    System.out.print(number);
    ++number;

      if(number >= n){
        break outer;                 // break inner would be equivalent to what you had
      }
   }

  System.out.println();

}

However, these break statements with labels look suspiciously similar to gotos, and gotos are frowned upon. A more teacher-friendly version would be to use a boolean flag, and check the flag in each loop:

boolean finished = false; 
for(i = 1; i <= n && ! finished; ++i) {

  for(j = 1; j <= i && ! finished; ++j) {

    System.out.print(number);
    ++number;

      if (number >= n) {
         finished = true;  // no need to break - loops condition will now be false
      }
   }

  System.out.println();

}

Note that this introduces an extra newline, which you generally want to make sure that whatever you print next appears on a different line.

Another option is to simply complicate your initial condition, without any flags:

 for(i = 1; i <= n && number < n; ++i) {

  for(j = 1; j <= i; ++j) {
    System.out.print(number);
    ++number;
  }

  System.out.println();
}

I would recommend, for readability purposes, version 2. Additionally, I would write it as follows:

boolean finished = false; 
for(int i = 0; i < n && ! finished; ++i) {
  for(j = 0; j < i && ! finished; ++j) {    
    System.out.print(number++);
    if (number >= n) {
      finished = true;
    }
  }
  System.out.println();
}

The key differences are using 0 to n-1 counting to repeat something n times (most programmers are very accustomed to that, instead of counting from 1 to n), and defining loop variables within the for, so that trying to use them outside of their loops is an error. This helps to avoid accidental reuse of variables.

tucuxi
  • 17,561
  • 2
  • 43
  • 74
0
import java.util.Scanner;
public class Tester{
public static void main(String []args){
   Scanner in = new Scanner(System.in);

   int i, j;
   int n = in.nextInt();
   int number = 1;

   loop:
   for ( i = 1; i <= n; ++i){
      for ( j = 1; j <= i; ++j){
         System.out.print(number);
         ++number;

         if (number > n)
         {
               break loop;
         }
    }

    System.out.println();
}
     }
}
Jess R
  • 3
  • 3
0

by using a for loop with a nested one you can achieve it like this:

  1. you have a row which is incremented by 1 on each row (line)
  2. you have a column variable which is increasing by one on each line or row
  3. you have a number with start to print from 1 till the inputed number for example it was entered 12.
  4. in inner loop you need to check the column be less or equal to row and the incremented number be less the entered number.
Scanner in = new Scanner(System.in);
System.out.print("Enter a Number: ");
int n = in.nextInt();
int number = 1;

for (int row = 1; row <= n && number <= n; row++) {
    for (int column = 1; column <= row && number <= n; column++) {
        System.out.print((number++) + " ");
    }
    System.out.println();
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36