Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with loop in C

i'm trying to compute "2^0 + 2^1 + 2^2 + ... + 2^14", using the following program(i'm a newbie and can only compute a exponent by multiply itself a certain times). The result should be 32767, but i ran it and got 270566475, i thought for long but can't figure out why...

#include <stdio.h>

int main(void)
{
   int i, e, exponent, sum;

   e = 1;
   exponent = 1;
   sum = 1;

   for (i = 1; i <=14; i++)
   {
       for (e = 1; e <= i; e++)
       {
          exponent *= 2;
       }

       sum += exponent;
   }

   printf("%d\n", sum);

   return 0;
}

So what's wrong with this??? Thanks!!!

like image 272
asunnysunday Avatar asked Mar 06 '26 17:03

asunnysunday


2 Answers

You don't need the inner loop. Just execute exponent *= 2 once, directly inside the outer loop. BTW, I think you have to do it after the sum += ....

Also, you could start with sum = 0 and i = 0, which is closer to the math you described.

like image 126
Marcelo Cantos Avatar answered Mar 08 '26 06:03

Marcelo Cantos


Look at your inner loop by itself. It's trying to calculate, for one specific value of i, 2^i.

But exponent does not start at 1 every time. So you go into that loop with exponent already some very large value.

for (i = 1; i <=14; i++)
{
    exponent = 1;
    for (e = 1; e <= i; e++)
    {
        exponent *= 2;
    }

    sum += exponent;
}

Now you've reset exponent (which, to be clear, isn't the exponent at all but the calculated result) for each new power of 2.

like image 25
VoteyDisciple Avatar answered Mar 08 '26 07:03

VoteyDisciple