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
for j:= 2 to y do
for k:= 1 to z do
temp:= temp+(i*j*k);
writeln(temp);
readln;
end.
`
my understanding is like this:
- if we input x,y, then z with value 2,2,2, then the output will be 18
- in for variable k first looping is (1 x 1 x 1) = 1 and for second looping is (1 x 1 x 2) = 2
- in for variable j (1 x 2 x 2) = 4
- in for variable i ( 1 x 1 x 1) = 1 and for second looping is ( 2 x 2 x 2) = 8
if we sum 2 + 4 + 8 = 14, please help with the correction
>Solution :
First of all, temp is not initialized, so it can contain rubbish. You will need to fix it, by initializing temp with a value. In this answer I will assume that you have already fixed that bug and temp is initialized with 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.