Build a String in a Loop
Completed
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
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);
}
}