MHB How many times will this statment be run?

  • Thread starter Thread starter find_the_fun
  • Start date Start date
find_the_fun
Messages
147
Reaction score
0
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?
 
Physics news on Phys.org
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.
 
Evgeny.Makarov said:
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
 
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".
 
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:
View attachment 1619
 

Attachments

  • Screen Shot 2013-11-03 at 9.24.15 PM.png
    Screen Shot 2013-11-03 at 9.24.15 PM.png
    731 bytes · Views: 72
Namaste & G'day Postulate: A strongly-knit team wins on average over a less knit one Fundamentals: - Two teams face off with 4 players each - A polo team consists of players that each have assigned to them a measure of their ability (called a "Handicap" - 10 is highest, -2 lowest) I attempted to measure close-knitness of a team in terms of standard deviation (SD) of handicaps of the players. Failure: It turns out that, more often than, a team with a higher SD wins. In my language, that...
Hi all, I've been a roulette player for more than 10 years (although I took time off here and there) and it's only now that I'm trying to understand the physics of the game. Basically my strategy in roulette is to divide the wheel roughly into two halves (let's call them A and B). My theory is that in roulette there will invariably be variance. In other words, if A comes up 5 times in a row, B will be due to come up soon. However I have been proven wrong many times, and I have seen some...

Similar threads

Replies
4
Views
1K
Replies
4
Views
4K
Replies
5
Views
1K
Replies
18
Views
1K
Replies
1
Views
990
Replies
1
Views
2K
Replies
10
Views
3K
Back
Top