Click here to Skip to main content
16,004,602 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include <bits/stdc++.h> 
using namespace std; 
  int calculateSum(int n) 
{ 
        int sum = 0; 
          for (int i = 0; i < n; i++) { 
          // calculate 2^i 
         sum = sum + (1 << i); 
    } 
    return sum; 
} 
  int main() 
{ 
    int n = 10; 
    cout << "Sum of series of power of 2 is : "
         << calculateSum(n); 
} 



and ı wanted Scanf for N .
(1<<i) what="" that="" mean="" ?="" <<

<b="">What I have tried:

ı dont know C++ coding so
ı know c programming

What I have tried:

ı dont know C++ coding so
ı know c programming
Posted
Updated 20-Jan-21 22:35pm
v2

It is not clear if you need the C or the C++ version of the code.
  • C version

C
#include <stdio.h>
  
int calculateSum(int n)
{
  int sum = 0;
  for (int i = 0; i < n; i++)
  {
    // calculate 2^i 
    sum = sum + (1 << i);
  }
  return sum;
}

int main()
{
  int n;
  printf("please enter N\n");
  if ( scanf("%d",&n ) == 1)
    printf("Sum of series of power of 2 is : %d\n", calculateSum(n));
}


  • C++ version

C++
#include <iostream>
using namespace std;

int calculateSum(int n)
{
  int sum = 0;
  for (int i = 0; i < n; i++)
  {
    // calculate 2^i 
    sum = sum + (1 << i);
  }
  return sum;
}

int main()
{
  int n;
  cout << "please enter N\n";
  cin >> n;
  cout << "Sum of series of power of 2 is : " << calculateSum(n) << "\n";
}



Notes
  • The sum can quicky overflow the variables

  • The function can be rewritten, more concisely, this way:
    C++
    int calculateSum(int n)
    {
      return ( (1 << n) - 1);
    }

 
Share this answer
 
All C code works in C++. But you should learn the C++ way to do things in time.

This is valid C++.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900