Print a sequence of numbers adding one number each time

I need to write a programm that, when inserted a number, it print a sequence of numbers from 1 to that number, in separate lines adding a number each time.
Example: if you insert 8, it print

1
1 2
1 2 3
1 2 3 ... 8
import java.util.Scanner;
public class Series {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);
        System.out.print("Insert number ");
            int a = sc.nextInt();
            int i = 0;
        StringBuilder sb = new StringBuilder();
            for(i=1; i<=a; i++)
                sb.append(i);
        System.out.println(sb.toString());
            
    }

}

I’m using this and obviously it print just one line from 1 to the number. I don’t know what i can change, or if this is totally wrong

New contributor

matteo panaro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

  • You’ve appended all numbers into StringBuilder but printed the result only once after the loop, which outputs the entire sequence in one single line, not step-by-step as you want.
  • Also, the numbers were appended directly without any space, resulting in a single concatenated string like 12345

Here is the corrected version:

import java.util.Scanner;

public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Insert number: ");
        int a = sc.nextInt();
        sc.close();

        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= a; i++) {
            sb.append(i).append(" ");
            System.out.println(sb.toString().strip());
        }
    }
}

Result

Insert number: 10
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

  • We should have added an if condition and avoided using strip() (or trim()) here for efficiency:
import java.util.Scanner;

public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Insert number: ");
        int a = sc.nextInt();
        sc.close();

        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= a; i++) {
            if (i > 1) {
                sb.append(" ");
            }

            sb.append(i);
            System.out.println(sb.toString());
        }
    }
}


  • Without using StringBuilder():
import java.util.Scanner;

public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Insert number: ");
        int a = sc.nextInt();
        sc.close();

        if (a < 1) {
            System.out.println("");
            return;
        }

        String res = "1";
        System.out.println(res);
        for (int i = 2; i <= a; i++) {
            res += " " + i;
            System.out.println(res);
        }
    }
}


  • Using two-loops approach is more memory-efficient as it avoids using StringBuilder(). The numbers are printed directly as they are processed, with no intermediate storage required.
import java.util.Scanner;

public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Insert number: ");
        int a = sc.nextInt();
        sc.close();

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

Notes

I would recommend making a habit of calling one of the String#strip…
methods rather than trim. See the post: Java’s String.trim has a
strange idea of whitespace. And see more discussion on this Answer of
mine. – Comment from Basil Bourque

The trim() or if can be avoided by starting with “1” in the
StringBuilder and looping from 2 on. (actually I would suggest using
a plain String instead of a SringBuilder) – by
user85421

4

You could also do it like this sans StringBuilder. And I don’t see the need to trim the white space unless it is a requirement.

Scanner scanner = new Scanner(System.in);
System.out.print("Insert number ");
int max = scanner.nextInt();

String s = "";
for (int i = 1; i <= max; i++) {
    s += i + " ";
    System.out.println(s);
}

If you must trim the trailing white space you could do the following since there is only one space to remove.

  System.out.println(s.substring(0, s.length()-1));

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật