C Program to print the following series. 1 3 7 15 31 . . . . . . . upto n times
Objective
Write a C program to print the binary exponential summation series: 1 3 7 15 31 ..... n times.
Algorithm / Approach
- Read an integer
n. - Initialize
value = 0. - Run a loop
ifrom 0 ton. - In each iteration, calculate the next term by adding 2i to the previous value:
value = value + pow(2, i). - Print the
value.
main.c
#include<stdio.h>
#include<math.h>
int main( ) {
int n, i, value=0;
printf("Enter Value for N : ");
scanf("%d", &n);
for(i=0; i<=n; i++) {
value = value + pow(2, i);
printf("%d ", value);
}
printf("\n");
return 0;
}
Expected Output
Enter Value for N: 6 1 3 7 15 31 63
Explanation of the Program
- This series generates numbers where the difference between terms is growing exponentially: +2, +4, +8, +16.
- By using the
pow()function frommath.h, we generate the powers of 2 (20=1, 21=2, 22=4) and continuously add them to a running total to build the sequence.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)