Web Development



How Does This Simple C Program Work?

By sanks4545 ·
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");

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?


This conversation is currently closed to new comments.

Thread display: Collapse - | Expand +

All Answers

Collapse -

It's taking advantage of a bit of math

by Tony Hopkinson 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 -

Reponse To Answer

by sanks4545 In reply to It's taking advantage of ...

Makes much more sense now, thanks!

Collapse -

Simple repeative multiple to raise a number to a power

by SLHINC 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

Related Forums