Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print the following series 1 2 3 4 ... n

Java Code Example — Series Programs

ADVERTISEMENT

Java Program to print the following series 1 2 3 4 ... n

Objective

Write a Java program to print the natural number series 1, 2, 3, 4 ... N.

Algorithm / Approach

  1. Prompt the user to enter the upper limit N.
  2. Read the integer n using a Scanner.
  3. Start a for loop with i initialized to 1.
  4. Run the loop as long as i ≤ n.
  5. In each iteration, print the value of i followed by a space.
  6. Increment i by 1 (i++).
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter N: ");
  int n = s.nextInt();
  for(int i = 1; i<=n; i++) {
   System.out.print(i+"  ");
  } 
 }
}

Expected Output

Enter N: 10
1  2  3  4  5  6  7  8  9  10

Explanation of the Program

  • This is the most fundamental sequence generation program, outputting consecutive positive integers.
  • The loop bounds define the sequence: starting strictly at 1 and ending at the user-defined limit.
  • We use System.out.print() instead of println() so the sequence stays on a single line separated by spaces.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT