Skip to main content

ProwessApps

Learn · Practice · Excel

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

C++ Code Example — Series Programs

ADVERTISEMENT

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

Objective

Write a C++ program to print the exponential sum series: 1, 3, 7, 15, 31 ... N.

Algorithm / Approach

  1. Include <math.h>.
  2. Initialize value = 0.
  3. Run a loop i from 0 to n.
  4. Calculate the power of 2 and add it to the running value: value = value + pow(2, i).
  5. Print the value.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
int main() {
 int n,value=0;
 cout<<"Enter the Value for N : ";
 cin>>n;
 for(int i = 0; i< n; i++) {
  value = value + pow(2,i);
  cout<< value<<"  ";
 }
 cout<< endl;
return 0;
}

Expected Output

Enter the Value for N : 5
1  3  7  15  31

Explanation of the Program

  • This is a cumulative binary sequence.
  • The powers of 2 are 1, 2, 4, 8, 16. If you keep a running sum of these powers (0+1=1, 1+2=3, 3+4=7, 7+8=15), you generate the mathematical formula (2n - 1).

Complexity

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