Numerical pattern | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Numerical pattern

I want to make a numerical pattern, like the example below. (The input depends on the user input). Example1: Input: 6 The required output would be: 1 23 456 Example2: Input: 7 The required output would be: 1 23 456 7 This is my code: https://code.sololearn.com/cA0a25a10A12

28th May 2021, 8:15 AM
Brianna
6 Answers
+ 1
for(int i = 1; i <= single; i++) { for(int j = 1; j<=i; j++) { if(number<=single) //add this System.out.print(number); number++; } System.out.println(); } //This works , printing only required numbers .. but for efficient code, should break loop when number >input.. I try to add it later.. edit: Brianna perfectly works this.. hope it helps for(int i = 1; i <= single; i++) { for(int j = 1; j<=i && number<=single; j++) { System.out.print(number+" "); number++; } System.out.println(); }
28th May 2021, 10:11 AM
Jayakrishna 🇮🇳
+ 1
Denise Roßberg hat java einen stream von 1 bis n?
28th May 2021, 9:27 AM
Oma Falk
Oma Falk - avatar
0
import java.util.Scanner; class Main{ public static void main(String args[]){ Scanner input= new Scanner(System.in); int single; int number = 1; single= input.nextInt(); for(int i = 1; i <= single; i++) { for(int j = 1; j<=i; j++) { System.out.print(number); number++; } if (number==single){ break; } System.out.println(); } } }
28th May 2021, 8:33 AM
Eashan Morajkar
Eashan Morajkar - avatar
0
What if you input 7 what is the required output? (break inner loop when single==number,.. and it works ..)
28th May 2021, 8:56 AM
Jayakrishna 🇮🇳
0
Example1:When the user inputs: 6. The output should be: 1 23 456 Example2: When the user inputs: 7 The output should be: 1 23 456 7
28th May 2021, 9:04 AM
Brianna
0
Frogged Yes. import java.util.stream.IntStream; for int nums and LongStream for long nums IntStream.range(1,n) or to include n you can also use rangeClosed(1,n) IntStream.rangeClosed(1,6).forEach(i -> { //do something with i });
28th May 2021, 1:51 PM
Denise Roßberg
Denise Roßberg - avatar