# Web Development

## Question

Locked

### How Does This Simple C Program Work?

By ·
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 <stdio.h>
#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!

This conversation is currently closed to new comments.

Thread display: Collapse - | Expand +

Collapse -

### It's taking advantage of a bit of math

by In reply to How Does This Simple C Pr ...

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

Collapse -

Makes much more sense now, thanks!

Collapse -

### Simple repeative multiple to raise a number to a power

by In reply to How Does This Simple C Pr ...

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

## Related Discussions

• 12

• 23

• 4

-Downing ·

• 4

PattyTech ·

• 2

#### How can I get high quality backlinks and improve my website rank?

Affiliatelance ·