Welcome to our community

Be a part of something great, join today!

How many times will this statment be run?

find_the_fun

Active member
Feb 1, 2012
166
Consider the following program segment where i,j and k are integer variables
for i := 1 to 12 do
for j := 5 to 10 do
for k := 15 downto 8 do
printf (i-j)*k

How many time is the print statement executed?

I thought it would be 12x5x7 but the answer key has 576?
 

Evgeny.Makarov

Well-known member
MHB Math Scholar
Jan 30, 2012
2,492
If "for j := 5 to 10" runs 10 - 5 = 5 times, then why are you saying that "for i := 1 to 12" runs 12 times?

See off-by-one error in Wikipedia.
 

find_the_fun

Active member
Feb 1, 2012
166
If "for j := 5 to 10" runs 10 - 5 = 5 times, then why are you saying that "for i := 1 to 12" runs 12 times?

See off-by-one error in Wikipedia.
Isn't the question ambiguous? For example "for i := 1 to 12" you don't know if another iteration will occur at 12 i.e. you don't know if it's i < 12 or i <= 12
 

Evgeny.Makarov

Well-known member
MHB Math Scholar
Jan 30, 2012
2,492
Well, I have not seen a programming language where a construction similar to "for i := m to n", without explicitly using < or ≤, runs the last iteration for i = n - 1. For example, in Fortran, the code

Code:
do i=1,10
  print*,i**2
end do
runs 10 times. The same thing happens in Pascal with "for i := 1 to 10 do".
 

Jameson

Administrator
Staff member
Jan 26, 2012
4,040
Interesting question.

I did a test in Matlab and it seems to run both the lower bound and the upper bound (obviously everything in between as well).

The very inefficient code:
Code:
testmatrix = [];
for i=5:10;
    testmatrix = [testmatrix;i];
end;
Outputs:
Screen Shot 2013-11-03 at 9.24.15 PM.png