Write a Program to print given series:1 2 4 8 16 32 64 128

By | June 14, 2021

In this programming tutorial, we will learn how to print the following sequence using C, C++, and Python programming languages.

The Sequence:

Vamware
1 2 4 8 16 32 64 128 265 .........

As you can see that the sequence starts for 1, and every next number is twice its first number.

Now we will write a script that will ask its user to enter a number n that will define the length of series or number of elements present in that sequence.

Example 1

let say if the user enters 5 then the output must series must have 5 numbers.

Input n= 5

Output 1 2 4 8 16

Example 2

Input n=9
Output 1 2 4 8 16 32 64 128 265

C Program to print given series: 1 2 4 8 16 32 64 128

#include <stdio.h>

int main() 
{
   int n, sequence=1;
   
   //enter the length of sequence
   printf("Enter the length of Series: ");
   scanf("%d", &n);
   
   while(n!=0)
   {
   	printf("%d ", sequence);
   	sequence*=2;
   	n-=1;
   }
   return 0;
}

Output

Enter the length of Series: 10
1 2 4 8 16 32 64 128 256 512

C++ Program to print given series:1 2 4 8 16 32 64 128

#include <iostream>
using namespace std;
 
int main() 
{	int n, sequence =1;
   //enter the length of sequence
   cout<<"Enter the length of Series: "; cin>>n;
   
   while(n!=0)
   {
   	cout<<sequence<<" ";
   	sequence*=2;
   	n-=1;
   }
   return 0;
}

Output

Enter the length of Series: 6
1 2 4 8 16 32

Python Program to print given series: 1 2 4 8 16 32 64 128

# enter the length of sequence
n = int(input("Enter the length of Series: "))

sequence=1

while(n):
    print(sequence, end =" ")
    sequence*=2
    n-=1

Output

Enter the length of Series: 11
1 2 4 8 16 32 64 128 256 512 1024

Complexity Analysis

  • Time Complexity:¬†O(N), where N is the total length of the series.
  • Space Complexity: O(1), constant space complexity.

Wrapping Up!

In this tutorial, we learned how to print the following sequence 1 2 4 8 16 32 64 128 ...... in 3 different programming languages. In the program, we asked the user to enter the length of the series and print the series according to the user-entered value.

Happy learning 

If you like this article or have any suggestions please let us know by commenting down below.

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *