Home > Software engineering >  For looping in Pascal
For looping in Pascal

Time:12-20

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:

  1. If we input x, y and z with values 2, 2 and 2 the output will be 18.
  2. In the 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.
  3. In the for variable j it is (1 x 2 x 2) = 4.
  4. In the 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.

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 to x
  • j is looping from 2 to y
  • k is looping from 1 to z

Each time their product is added to temp.

x=2, y=2, z=2

  • i is 1
    • j is 2
      • k is 1
        • we add 1 * 2 * 1 = 2 to temp, resulting in 2
      • k is 2
        • we add 1 * 2 * 2 = 4 to temp, resulting in 2 4 = 6
  • i is 2
    • j is 2
      • k is 1
        • we add 2 * 2 * 1 = 4 to temp, resulting in 6 4 = 10
      • k is 2
        • we add 2 * 2 * 2 = 8 to temp, resulting in 10 8 = 18

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.

  • Related