473,836 Members | 1,522 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I exit a for loop in C#

What is the sytax for exiting a for loop in C#?
Nov 16 '05 #1
65 65090
try "break;"
"Aaron Ackerman" <no**@nospam.co m> дÈëÏûÏ¢
news:#1******** *****@tk2msftng p13.phx.gbl...
What is the sytax for exiting a for loop in C#?

Nov 16 '05 #2
"Aaron Ackerman" <no**@nospam.co m> wrote in message
news:%2******** *******@tk2msft ngp13.phx.gbl.. .
What is the sytax for exiting a for loop in C#?


continue; will stop processing in the current loop and jump straight to the
next

break; will exit the entire loop
Nov 16 '05 #3
"Aaron Ackerman" <no**@nospam.co m> wrote in message news:<#1******* ******@tk2msftn gp13.phx.gbl>.. .
What is the sytax for exiting a for loop in C#?


for(..)
{
...
break;
}

Aaron
Nov 16 '05 #4
On Mon, 5 Apr 2004 23:00:15 -0400, "Aaron Ackerman" <no**@nospam.co m>
wrote:
What is the sytax for exiting a for loop in C#?


To be picky, you should use a while loop and include whatever would
cause an exit from your for loop in the loop condition of the while
loop.
Nov 16 '05 #5
Brady Kelly <bk****@icom-it.co.za> wrote:
What is the sytax for exiting a for loop in C#?


To be picky, you should use a while loop and include whatever would
cause an exit from your for loop in the loop condition of the while
loop.


I disagree on that. There are *loads* of times where you basically just
want to get out of a loop at a certain point - and that may be
different points in the execution of the block within the loop.

It's one of those "rules" which might sound okay in principle, but ends
up making the code completely unreadable in practice.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
On Mon, 5 Apr 2004 23:00:15 -0400, "Aaron Ackerman" <no**@nospam.co m>
wrote:
What is the sytax for exiting a for loop in C#?


To be picky, you should use a while loop and include whatever would
cause an exit from your for loop in the loop condition of the while
loop.
Nov 16 '05 #7
Brady Kelly <bk****@icom-it.co.za> wrote:
What is the sytax for exiting a for loop in C#?


To be picky, you should use a while loop and include whatever would
cause an exit from your for loop in the loop condition of the while
loop.


I disagree on that. There are *loads* of times where you basically just
want to get out of a loop at a certain point - and that may be
different points in the execution of the block within the loop.

It's one of those "rules" which might sound okay in principle, but ends
up making the code completely unreadable in practice.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
BREAKS in a FOR loop means that you should have picked a WHILE loop instead.

If you accept McConnell's work in Code Complete as the style authority for
software construction - see section 15. The FOR loop is to be used when the
number of iterations is know aforehand.

"The FOR loop is for simple loops. Most complicated looping tasks are
better handled by the WHILE loop." (pg 329)

"Limiting yourself to only one statement to control a loop's exit consdition
is a powerful way to simplify your loop." (pg 328)

While you may disagree or have a personal preference or can cite some
specific instance to the contrary, Code Complete is hard to agrue with
because :
1) It's adopted by a lot of programmers and their repsective shops
2) The goal IS to create readable code (i.e. easier to understand, easier to
maintain)
3) While opinions relating to programming style issues are like ears (every
one has at least two), McConnell certainly established the baseline - and
one has to build a strong case for the exceptions.

that's the way i see it, but i could be completly wrong.

regards
roy fine
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
Brady Kelly <bk****@icom-it.co.za> wrote:
What is the sytax for exiting a for loop in C#?


To be picky, you should use a while loop and include whatever would
cause an exit from your for loop in the loop condition of the while
loop.


I disagree on that. There are *loads* of times where you basically just
want to get out of a loop at a certain point - and that may be
different points in the execution of the block within the loop.

It's one of those "rules" which might sound okay in principle, but ends
up making the code completely unreadable in practice.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #9
Roy Fine <rl****@twt.obf uscate.net> wrote:
BREAKS in a FOR loop means that you should have picked a WHILE loop instead.
Not necessarily. When there are multiple places in the loop where you
might want to break, it can be a complete pain to recode that as a
while loop. Either you end up with a horrendously large condition, or
you end up with a temporary variable which only serves to let you break
out - in which case you might as well break out directly, in my view.
If you accept McConnell's work in Code Complete as the style authority for
software construction - see section 15. The FOR loop is to be used when the
number of iterations is know aforehand.
I don't accept Code Complete to be flawless in every particular. That
seems a very bold statement about the for loop which would certainly
need more backing up than what you've presented. He's stated that *he*
likes to use the for loop only for simple loops, but at least in the
passages you've quoted, he hasn't stated *why*.
"The FOR loop is for simple loops. Most complicated looping tasks are
better handled by the WHILE loop." (pg 329)

"Limiting yourself to only one statement to control a loop's exit consdition
is a powerful way to simplify your loop." (pg 328)
Well, I disagree.
While you may disagree or have a personal preference or can cite some
specific instance to the contrary, Code Complete is hard to agrue with
because :
1) It's adopted by a lot of programmers and their repsective shops
That doesn't mean that every bit of it is absolutely perfect though,
does it? It makes sense to adopt most of a coding standard which you
mostly agree with, but not take the whole thing without allowing
yourself to disagree with any part of it.
2) The goal IS to create readable code (i.e. easier to understand, easier to
maintain)
On that we agree.
3) While opinions relating to programming style issues are like ears (every
one has at least two), McConnell certainly established the baseline - and
one has to build a strong case for the exceptions.


The exceptions seem pretty obvious to me. Here's an example - the task
is to see whether or not a string looks like a valid decimal number.
The rules are (for the purposes of this case):

o No whitespace anywhere
o No + or - (as that can be dealt with more effectively outside the
loop)
o A single decimal point is allowed (only allow '.' not ',')
o All other characters must be in the range '0'-'9'

To me, the simplest way of expressing that in C# is:

public static bool IsDecimal (string data)
{
bool gotPoint = false;

foreach (char c in data)
{
if (c != '.' && (c < '0' || c > '9'))
{
return false;
}
if (c=='.')
{
if (gotPoint)
{
return false;
}
gotPoint = true;
}
}
return true;
}

An alternative might be:

public static bool IsDecimal (string data)
{
bool gotPoint = false;

foreach (char c in data)
{
if (c=='.')
{
if (gotPoint)
{
return false;
}
gotPoint = true;
continue;
}
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}

(Obviously the foreach can be easily recoded as a "real" for if you
want.)

What is the more readable while loop here?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
5419
by: drose0927 | last post by:
Please help! I can't get my program to exit if the user hits the Escape button: When I tried exit(EXIT_SUCCESS), it wouldn't compile and gave me this error: Parse Error, expecting `'}'' 'else if (choice == 27) exit(0) } }' Here is my program (Simple loop to display currency equivalencies based
8
10768
by: Edwinah63 | last post by:
Hi Everyone, in vb6 i was able to execute the following code and it would close the children is the reverse order they were opened eg the last child opened was the first child to close. in mdiparent i had this code i = Forms.Count - 1 Do Until i = 0
4
2144
by: Microsoft | last post by:
I have a for loops that goes from 1 to 256 I test the number and exception is thrown if there is an error. How do I get the program to stop in the middle of the loop and go to the next increment if an exception is thrown. I can only figure out how to exit the loop. 'read the text file
32
2616
by: cj | last post by:
When I'm inside a do while loop sometimes it's necessary to jump out of the loop using exit do. I'm also used to being able to jump back and begin the loop again. Not sure which language my memories are of but I think I just said loop somewhere inside the loop and it immediately jumped back to the start of the loop and began again. I can't seem to do that in .net. I this functionality available?
44
4320
by: James Watt | last post by:
can anyone tell me how to do an infinite loop in C/C++, please ? this is not a homework question .
2
2102
by: nabman | last post by:
I am reading a txt file, I have a txt file(customers.txt) that is read, with account numbers and passwords. Once the user enters a account number and password it should read the file and if there in there it will show the second form and end the loop. The probelm I am having is when I enter a acct # and password that is maybe the third entry in the file it is hitting the "else" statment and displaying my msgbox. What is the code I can put in...
11
3019
by: Andreig | last post by:
Gentlemen I cannot figure out the following: I have a loop inPrivate Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint Pressing a key I am checking what key was pressed and come back to the loop. Thanks for help
4
2688
by: kenneth6 | last post by:
for(int i=0; i<100; i++) { if(mark==TMark) { return i; cout << i << endl; break; } else {
11
12182
by: icarus | last post by:
Hi, this is a simple temperature converter (Fahrenheit to Celsius to Kelvin). Using gcc 4.0. The user is supposed to enter q or any other non-character to exit the program. Problem with this code: I enter 'q' as soon as the program starts. It hangs. Then run it again. Enter a number, it executes fine. But when I enter q, it repeats last number and it doesn't 'pay attention' to the letter
7
2728
by: csharpula csharp | last post by:
Hello, I am iterating through objects and have the following case: foreach (classA objectA in classAList) { if (classA.count0) { //now I need to get out of the foreach loop if so,otherwise to keep iterating
0
9668
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10844
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10590
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9374
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7791
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6979
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4016
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3113
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.