Java Program to print the following series. 3 6 9 12... n
Objective
Write a Java program to print the multiples of 3 series: 3, 6, 9, 12 ... up to N terms.
Algorithm / Approach
- Read the number of desired terms
Nfrom the user. - Start a
forloop fromi = 1up ton. - Inside the loop, multiply
iby 3 (3 * i). - Print the computed product.
- Repeat until
nterms are generated.
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((3*i)+" ");
}
}
}
Expected Output
Enter N: 6 3 6 9 12 15 18
Explanation of the Program
- Notice that
Nin this program represents the *number of terms*, not the maximum value. - If the user inputs 6, the loop runs 6 times, producing the first 6 multiples of 3.
- The mathematical formula for the i-th term in an arithmetic progression where the common difference is 3 is simply
3 * i.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)