C#
  Home arrow C# arrow Page 4 - 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 
Dedicated Servers 
Moblin 
JMSL Numerical Library 
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 - The goto Statement


    (Page 4 of 6 )

    The go to statement, or as C# presents it now, the 'goto' statement, has been in programming languages for a very long time. Many programmers avoid using the goto statement because they think it produces ugly code or code that can turn the application upside down.  Actually, the problem is not the goto statement itself, it's using the statement incorrectly. If you know exactly how to use the goto statement, it will save you a great deal of time. I will use the EVEN/ODD Numbers program to present the goto statement, but first, look at the following code.

    static void Main(string[] args)
    {
      int x = 0;
      Console.WriteLine("Please enter a number, -1 to exist");
      x = Convert.ToInt32(Console.ReadLine());
      while( x != -1) 
      { 
        if(x % 2 == 0) 
        { 
          Console.WriteLine("This is an EVEN number"); 
        } 
        else 
        { 
          Console.WriteLine("This is an ODD number"); 
        } 
        
    Console.WriteLine("Please enter a number, -1 to exist");
        x = Convert.ToInt32(Console.ReadLine()); 
      } 
    }

    This is fine, and it will compile and run, but this code has some problems. The first problem is that there are duplicate statements, because the program needs the value of the number before the while loop so it can test its Boolean expression, and it needs it again at the end of the iteration to set the new value of x. Actually, well designed code for this kind of problem states "I read a value then if it passes the Boolean Expression I process the value and if not I stop." This is not the case in our little program, because we read the value once before the loop, and again inside the loop, so we need to rewrite the above code:

    using System;
    namespace MyCompany
    {
      public class Loops
      {
        static void Main(string[] args)
        {
          int x = 0; 
          while(true) 
          { 
            Console.WriteLine("Please enter a number, -1 to exist"); 
            x = Convert.ToInt32(Console.ReadLine()); 
            if(x == -1) 
            { 
              goto exist; 
            } 
        

            if(x % 2 == 0) 
            { 
              Console.WriteLine("This is an EVEN number"); 
            } 
            else 
            { 
              Console.WriteLine("This is an ODD number"); 
            } 
          } 

          exist: 
          { 
            Console.WriteLine("Program exist, press the enter key"); 
            Console.ReadLine(); 
          } 
        } 
      } 
    }

     
    Compile and run the application and you will get the following result:

    As you can see, we get the same result, but the code is a little different from before. Note that we have used the true keyword with the while statement, so it will evaluate to true, and it results in an infinite loop; the value will be tested, and if it's -1, we jump to the label exist using the goto keyword, which terminates the application. You may say that you can use the break statement instead of goto, and we will get the same results, and yes, you are correct in this example -- but there are times where you have more than one label, and you need to jump to them depending upon the value you have. Another famous use of the goto statement is with the switch case statement, so let's take an example.

    static void Main(string[] args)
    {
      int x = Convert.ToInt32(Console.ReadLine());
      bool result = (x % 2 == 0);
      switch(result)
      {
        case true:
          Console.WriteLine("EVEN NUMBER");
          goto default;
        case false:
          Console.WriteLine("ODD NUMBER");
          goto default;
        default:
          Console.WriteLine("hit the Enter key to exist");
          Console.ReadLine();
          break;
      }
    }

    This is another variation of the EVEN/ODD Number story, but this time we used a switch statement to check if it's an even or odd number, and in either case we goto the default section, where we write the line "hit the Enter key to exist" and wait until the user does just that. Note that there are no break statements in the first two case statements because they don't actually need them; either case will end up in the default section, which actually needs the break statement to exist. When you know how to use the goto statement, it will save you a great deal of time when your algorithm is complex.

    More C# Articles
    More By Michael Youssef


     

    C# ARTICLES

    - 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...
    - Color Transformation in C# GDI+ Programming
    - Exceptions in C#
    - Overriding versus Overloading
    - Value Types and Reference Types
    - Defining Member and Type Visibility
    - Managing Files in C#
    - Working with Windows Registry in C#
    - Lossless Image Resizing in C#
    - Lossless Image Converting in C#
    - Creating an RSS Feed with ASP.Net Written in...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway