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,yandzwith values2,2and2the output will be18. - In the
forvariablekthe first looping is (1 x 1 x 1) = 1 and for the second looping it is (1 x 1 x 2) = 2. - In the
forvariablejit is (1 x 2 x 2) = 4. - In the
forvariableiit 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.
iis looping from 1 toxjis looping from 2 toykis looping from 1 toz
Each time their product is added to temp.
x=2, y=2, z=2
iis 1jis 2kis 1- we add 1 * 2 * 1 = 2 to
temp, resulting in 2
- we add 1 * 2 * 1 = 2 to
kis 2- we add 1 * 2 * 2 = 4 to
temp, resulting in 2 4 = 6
- we add 1 * 2 * 2 = 4 to
iis 2jis 2kis 1- we add 2 * 2 * 1 = 4 to
temp, resulting in 6 4 = 10
- we add 2 * 2 * 1 = 4 to
kis 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.
