Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print the following series. 1 3 7 15 31... n

Java Code Example — Series Programs

ADVERTISEMENT

Java Program to print the following series. 1 3 7 15 31... n

Objective

Write a Java program to print the series 1, 3, 7, 15, 31 ... for N terms.

Algorithm / Approach

  1. Read the number of terms n from the user.
  2. Initialize an integer accumulator x to 0.
  3. Start a for loop with i = 0 up to n - 1.
  4. In each iteration, calculate 2 raised to the power of i using Math.pow(2, i).
  5. Add the powered result to x.
  6. Print x.
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();
  int x = 0;
  for(int i = 0; i< n; i++) {
   x = x + (int) Math.pow(2,i);
   System.out.print(x+"  ");
  } 
 }
}

Expected Output

Enter N: 5
1  3  7  15  31

Explanation of the Program

  • This series corresponds to the cumulative sum of powers of 2 (20, 21, 22...).
  • Let's trace the logic: when i=0, we add 20 (1) to x, giving 1. When i=1, we add 21 (2) to x (which was 1), giving 3. When i=2, we add 22 (4) to x (which was 3), giving 7.
  • Alternatively, you can notice that the i-th term in this series is always exactly 2i - 1 (for i starting at 1).

Complexity

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

Common Mistakes

  • Forgetting to cast Math.pow() to an int. The Math.pow function in Java returns a double, which cannot be directly assigned to an int without explicit casting.
ADVERTISEMENT