Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For looping in Pascal Languange

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. if we input x,y, then z with value 2,2,2, then the output will be 18
  2. in for variable k first looping is (1 x 1 x 1) = 1 and for second looping is (1 x 1 x 2) = 2
  3. in for variable j (1 x 2 x 2) = 4
  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.

  • 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading