program exercise1;
uses crt;
var
x,y,z,i,j,k,temp : integer;
begin
clrscr;
write('input x: ');readln(x);
write('input y: ');readln(y);
write('input z: ');readln(z);
for i:= 1 to x do { (1 x 1 x 1) = 1 and (2 x 2 x 2) = 8 }
for j:= 2 to y do { (1 x 2 x 2) = 4 }
for k:= 1 to z do { (1 x 1 x 1) = 1 and (1 x 1 x 2) = 2 }
temp:= temp+(i*j*k);
writeln(temp); { should be 14, but is 18 instead }
readln;
end.
My understanding is like this:
x
, y
and z
with values 2
, 2
and 2
the output will be 18
.for
variable k
the first looping is (1 x 1 x 1) = 1 and for the second looping it is (1 x 1 x 2) = 2.for
variable j
it is (1 x 2 x 2) = 4.for
variable i
it is (1 x 1 x 1) = 1 and for the second looping it is (2 x 2 x 2) = 8.But the sum (2 + 4 + 8) should be 14
- please help with the correction.
I would strongly recommend the initialization of temp
to 0, the subsequent reasoning will assume that the initial value of temp
was 0.
x
, y
and z
are user-defined values.
i
is looping from 1 to x
j
is looping from 2 to y
k
is looping from 1 to z
Each time their product is added to temp
.
i
is 1
j
is 2
k
is 1
temp
, resulting in 2k
is 2
temp
, resulting in 2 + 4 = 6i
is 2
j
is 2
k
is 1
temp
, resulting in 6 + 4 = 10k
is 2
temp
, resulting in 10 + 8 = 18You have missed the case of (2 x 2 x 1), this is why you reached 14 instead of 18. In order to analyze problems such as this one, it is recommendable to either take a pen & paper and go through it step-by-step, or debug your code using a debugger.