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
- Prompt the user to enter the upper limit
N. - Read the integer
nusing aScanner. - Start a
forloop withiinitialized to 1. - Run the loop as long as
i ≤ n. - In each iteration, print the value of
ifollowed by a space. - Increment
iby 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 ofprintln()so the sequence stays on a single line separated by spaces.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)