It is not clear if you need the
C
or the
C++
version of the code.
#include <stdio.h>
int calculateSum(int n)
{
int sum = 0;
for (int i = 0; i < n; 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));
}
#include <iostream>
using namespace std;
int calculateSum(int n)
{
int sum = 0;
for (int i = 0; i < n; 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