Question Locked

How Does This Simple C Program Work?

0 helpful
4 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I know this may not be the right website to post coding questions but hey, I'm signed up at 2000000 different websites, so I'm avoiding signing up somewhere else!

Anyway, how does this program calculate the given table of 2^n power?

#include
#define N 20

int main(void) {
int n;
int val = 1;

printf("\t n \t 2^n\n");
printf("\t================\n");

for(n=0; n<=N; n++) {
printf("\t %d \t %d\n", n, val);
val = 2*val;
}
return 0;
}

What I don't understand is how val*2, which I understand to mean val times 2, computes 2^n power. Why does it do that and not 2*val?

Thanks!

4 replies

by tony hopkinson

Powers as repeated multiplication, just like multiplcation is repeated addition.
Dry run it
n val val*2
0 1 2
1 2 4
2 4 8
3 8 16

Course seeing as it's powers of 2 could have bitwise shifted it with
val = 1 << 21;

2 ^ 4 = 2 * 2 * 2 * 2 = 16
it works because val is initialised to 1, ie it's already worked out 2^0 ...

edited to fix a small oops on my part

by cblackford

"2" is just the seed. Change it to "3" and look at the results.

This discussion is closed to new replies.