C#
  Home arrow C# arrow Page 6 - Branching and Looping in C#, Part 2
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Branching and Looping in C#, Part 2
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 38
    2005-04-19

    Table of Contents:
  • Branching and Looping in C#, Part 2
  • The while Loop
  • The do/while Loop
  • The goto Statement
  • The return statement
  • break and continue statements

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Branching and Looping in C#, Part 2 - break and continue statements


    (Page 6 of 6 )

    The break statement breaks the execution of the current statement block and executes the first line that follow the block. Usually you will find code like this:

    static void Main(string[] args)
    {
      int x = 0;
      for(;;)
      {
        x = Convert.ToInt32(Console.ReadLine());
        if(x == -1)
          break; 
        else
          Console.WriteLine("It's " + x);
      }
      Console.WriteLine("Program exist");
    }

    The code is simply an infinite for loop (infinite for loops constructed using empty expressions for all the parts as you can see), and inside the loop we use an if statement to test if the input number is -1; if so,  the for loop breaks, and execution begins at the first line after the for loop. You can check the message "Program exist" using CTRL + F5. The above code can be written using the while statement as follows:

    static void Main(string[] args)
    {
      int x = 0;
      while(true)
      {
        x = Convert.ToInt32(Console.ReadLine());
        if(x == -1)
          break;
        else
          Console.WriteLine("It's " + x);
      }
      Console.WriteLine("Program exist");
    }

    As you can see, the for(;;) loop is the same as while(true), but you need to use the break statement, or maybe your algorithm needs the goto statement in order to terminate the execution of the infinite loop, and continue on the first statement after the loop. As we saw before,  the break statement's primary use is with the switch statement, so I will not discuss it again. Before we end our discussion about the break statement, I want to distinguish between break and goto through code. Consider the following code:

    static void Main(string[] args)
    {
      for(;;)
      {
        Console.WriteLine("Enter a word");
        string temp = Console.ReadLine();
        Char[] tempChar = temp.ToCharArray();
        foreach(Char x in tempChar)
        {
          if(x == 'h')
            break;
          else
            Console.WriteLine(x);
        }
      }
    }

    This code takes a word from the user and writes every character in the word in a separate line. If the character is 'h', it breaks using the break statement. Now enter the following words and see what will happen: "Michael" then "Mic" then "h". Some of you will think that whenever the program encounters the 'h' it will terminate because of the break statement; the result is the following:

    As you can see, in the first word "Michael" the program prints only the characters before the character 'h'; in the second word "Mic" it prints all the characters; and in the third word (which is only the letter h) it will print nothing. Guess what? The loop is still here and the program didn't terminate. All of this happens because the break statement breaks only the current block, which in our case is the inner foreach block. So when it breaks the foreach loop, the infinite for loop iterates again and again, and it will never end. One perfect solution for this problem involves using the goto statement as follows:

    static void Main(string[] args)
    {
      for(;;) 
      {
        Console.WriteLine("Enter a word");
        string temp = Console.ReadLine();
        Char[] tempChar = temp.ToCharArray();
        foreach(Char x in tempChar)
        {
          if(x == 'h') 
            goto exist;
          else
            Console.WriteLine(x);
        }
      }

      exist:
        Console.WriteLine("the Program is terminating");
    }

    You will get the following result, as expected:

    This is one perfect use for the goto statement, where the break statement is not appropriate at all.

    C# features another keyword that must be discussed with the break statement; it's the continue statement. As you know, the break statement breaks the execution of the current loop and begins execution on the first line after the current loop. The continue statement differs from the break statement because it will not break the execution of the current loop; instead it will terminate the current iteration and begin a new iteration in the loop. In other words, the continue statement, when encountered in the loop, will escape the next statements in the iteration and go to the top of the loop to CONTINUE looping. Here is the same example as I used above, this time with continue instead of break and goto:

    static void Main(string[] args)
    {
      for(;;)
      {
        Console.WriteLine("Enter a word");
        string temp = Console.ReadLine();
        Char[] tempChar = temp.ToCharArray();
        foreach(Char x in tempChar)
        {
          if(x == 'h')
            continue;
          else
            Console.WriteLine(x);
        }
      }
    }

    Enter the word "Michael" and the see the result:

    What happened is that the program actually escaped the character 'h' and continued printing all the other characters without terminating the loop. As I said before, each statement fits inside a specific scenario, so use the continue statement when you need to escape a number of statements without the loop termination.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

     

    C# ARTICLES

    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#
    - Working with Regular Expressions in C#
    - Sending Simple E-Mail in C#
    - Building C# Comparable Objects: IComparable ...
    - Color Transformation Applications in C# GDI+...
    - Performing Color Transformation Operations i...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT