Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

For loop question

Status
Not open for further replies.

cjburkha

Programmer
Jul 30, 2004
76
0
0
US
Hi all,

I have a for loop that doesn't behave how I expect, and I was hoping someone could explain it for me...

I would expect the following loop to run exactly 1 time

Code:
dim times as integer = 2
dim i as integer = 0
for i = 0 to (times - 1)
	response.write("i is:" + i.toString + " ")
	times -= 1
next i

It runs two times for me.

I starts as 0, and runs through the loop to next i, where it gets incremented to 1. Now it comes to the top, evaluates that it is less than (times -1) and should not go through the loop again.

Where is my mistake in understanding how a for loop works?

Thanks for your help,

CJB
 
Because it runs for i = 0 to i = 1 which means that it will loop whilst it is one of those values (therefore it will loop while those values is either 0 or 1).




____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
Excellent, thank you very much. I expected

Code:
dim times as integer = 2
dim i as integer = 0
for i = 0 to (times - 1)
	response.write("i is:" + i.toString + " ")
	times -= 1
next i

response.write("<br>")

dim highCount as integer = 5
for i = 0 to highCount
	response.write("i is:" + i.toString + " ")
	highCount = 1
next i

to run like

Code:
	int times = 1;
	int i = 0;
	for (i=0;i<=times;i++) {
		Response.Write("i is:" + i + " ");
		times --;
	}
	Response.Write("<br>");
	int highCount = 5;
	for (i=0;i<=highCount;i++) {
		Response.Write("i is:" + i + " ");
		highCount = 1;
	}

But it does not. As long as I know that it doesn't, and why, all is good.

Thanks again,

CJB
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top