Please help me how to write a program in C to find sum of 2+4+8+....to 2 raised to power n using recession
Program in C language to add 2+4+8+....?
This uses recursion
#include %26lt;math.h%26gt;
unsigned int findSum(unsigned int n);
main()
{
int n = 3;
printf("%d\n",findSum(n));
}
unsigned int findSum(unsigned int n)
{
if(n == 0)
return 0; //this should be 1 since pow(2,0) is 1 but u asked 2+4+...ok
return (pow(2,n) + findSum(n-1));
}
please use -lm option to link with math.h since i used pow() function.
gcc xxx.c -lm
Reply:#include%26lt;stdio.h%26gt;
main()
{
int n,i,j,x,y;
printf("Number: ");
scanf("%d",%26amp;n);
for(i=0;i%26lt;=n;i++)
j=2n;
for(y=0;y%26lt;=j;y++)
x=y+j;
printf("sum: %d",x);
return 0;
}
Reply:If you want to have 10 members (else change thenumber 10)
int r=0;
int b=1;
for (i=1;i%26lt;=10;i++)
{
r+=b;
b=2*b; //or use shift command
}
Reply:Ok, this is a simple program to design so dont worry about it. First you'll need a variable called SUM which will contain the sum and through a for loop(from 1 to N) we'll increment the sum ... anyway heres the code, I've done it with C++, but you can switch it to C
int main()
{
//the sum
int sum;
//n - the inputed number-..
int n;
cin%26gt;%26gt;n;
//starting from 2 increment i by 2..which is 2, 4, 6...
for(int i = 2;i%26lt;n;i+2)
{
sum+=i;
}
//print the results out
cout%26lt;%26lt;sum;
}
Reply:for(int i=num;i%26gt;=1;i--)
{
sum += 2%26lt;%26lt;i;
}
sum +=2;
I hope this is the answer you are looking for
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment