Kashfi
Kashfi

Reputation: 46

How do you print the sequence one 1, then two 2, three 3, ... n ns?

Write a program that prints a part of the sequence:

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ...

(the number is repeated as many times, to what it equals to).

I've used two for loops, however, I can't get 1 to print once, 2 to print twice, instead, I get

1 2 3 4 5 6 1 2 3 4 5 6, etc.

Upvotes: 0

Views: 4612

Answers (4)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79055

Java 11+

If you are building your application with Java 11+, you can do it with a single loop by using String#repeat.

Demo:

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++)
            System.out.print(String.format("%s ", String.valueOf(i)).repeat(i));
    }
}

Output:

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

Online Demo

Upvotes: 1

palsega
palsega

Reputation: 61

As I remember the goal is to print n numbers (for example 1 2 2 3 3 3 4 for n = 7), diveded by space. Sorry for my java)), I wrote it in Kotlin, tried to change for Java, but main idea is clear. BTW n – the number of the elements, you need to read with Scanner.

int count = 0 //Idea is to create a counter, and to increment it each time of printing

for (int i = 0; i <= n; i++) { //Loops n times
    for (int j = 0; j < i; j++) { //Loops i times
        if (int count < int n) {
        System.out.print(" "+i+" ");
        int count++ //Prints 1 one time, 2 two times, etc. stops if reached n number
        }
    }
}

Upvotes: 1

Vimukthi
Vimukthi

Reputation: 880

You need two for loops for this.

for (int i = 0; i <= 5; i++) { // This will loop 5 times
    for (int j = 0; j < i; j++) { //This will loop i times
        System.out.print(i);
    }
}

Upvotes: 1

hem
hem

Reputation: 1032

How about this :

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

where, num = 1,2,....n

(Also we wont be able to tell why you got that output unless you attach the code. Please attach the code snippets for such questions :) !

Upvotes: 0

Related Questions