Problem with loop in C -


i'm trying compute "2^0 + 2^1 + 2^2 + ... + 2^14", using following program(i'm newbie , can compute exponent multiply times). result should 32767, ran , got 270566475, thought long can't figure out why...

#include <stdio.h>  int main(void) {    int i, e, exponent, sum;     e = 1;    exponent = 1;    sum = 1;     (i = 1; <=14; i++)    {        (e = 1; e <= i; e++)        {           exponent *= 2;        }         sum += exponent;    }     printf("%d\n", sum);     return 0; } 

so what's wrong this??? thanks!!!

look @ inner loop itself. it's trying calculate, 1 specific value of i, 2^i.

but exponent not start @ 1 every time. go loop exponent large value.

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

now you've reset exponent (which, clear, isn't exponent @ calculated result) each new power of 2.


Comments