Can you explain this code?
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:
- If we input
x
,y
andz
with values2
,2
and2
the output will be18
. - In the
for
variablek
the first looping is (1 x 1 x 1) = 1 and for the second looping it is (1 x 1 x 2) = 2. - In the
for
variablej
it is (1 x 2 x 2) = 4. - In the
for
variablei
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.
CodePudding user response:
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 tox
j
is looping from 2 toy
k
is looping from 1 toz
Each time their product is added to temp
.
x=2, y=2, z=2
i
is 1j
is 2k
is 1- we add 1 * 2 * 1 = 2 to
temp
, resulting in 2
- we add 1 * 2 * 1 = 2 to
k
is 2- we add 1 * 2 * 2 = 4 to
temp
, resulting in 2 4 = 6
- we add 1 * 2 * 2 = 4 to
i
is 2j
is 2k
is 1- we add 2 * 2 * 1 = 4 to
temp
, resulting in 6 4 = 10
- we add 2 * 2 * 1 = 4 to
k
is 2- we add 2 * 2 * 2 = 8 to
temp
, resulting in 10 8 = 18
- we add 2 * 2 * 2 = 8 to
The mistake in your calculation
You 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.