Given a
, b
and c
, calculate: 2^a + 2^b + 2^c
.
program power;
var a,b,c, r1,r2,r3 :integer;
procedure power2(pwr :integer; var result :integer);
var i :integer;
begin
i := 1;
result := 1;
while pwr <= i do
begin
result := result * 2;
i := i + 1;
end;
end;
begin {main}
write('a: ');
readln(a);
write('b: ');
readln(b);
write('c: ');
readln(c);
power2(a, r1);
power2(b, r2);
power2(c, r3);
writeln('power: ', r1 + r2 + r3);
end.
Why does the program fail to do the while
loop?
The program prints 3
instead of the sum of r1
, r2
, r3
, independently of the input (a,b,c). How do I fix this?
You are incorrect about the while loop comparison, pwr <= i
.
It should be the other way around.
procedure power2(pwr :integer; var result :integer);
var i :integer;
begin
i := 1;
result := 1;
while i <= pwr do
begin
result := result * 2;
i := i + 1;
end;
end;