Build a String in a Loop

Lab Java Beginner 10 points

Read n and print the numbers 1 to n joined by commas, using a StringBuilder.

Input

One integer ≥ 1.

Output

One line, e.g. 1,2,3.

Example

Input

5

Output

1,2,3,4,5
Sample input available Sample output available
Editor
Java

Hints

Add the comma before every number except the first.

Solution explanation

Concatenating Strings with + inside a loop creates a new String each time; StringBuilder avoids that.

Show solution
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            if (i > 1) {
                sb.append(',');
            }
            sb.append(i);
        }
        System.out.println(sb);
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD