Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » Control Statements in C#

Control Statements in C#

In this article I will explain you about different control statements in c#.

Author Rank:
Total page views :  1235
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


This article has been excerpted from book "Visual C# Programmer's Guide"

Control statements give you additional means to control the processing within the applications you develop. This section explores the syntax and function of the if, switch, do-while, for, foreach, goto, break, continue, and return statements.

If-then-else

The if statement has three forms: single selection, if-then-else selection, and multicase selection. Listing 5.23 contains an example of each form.

Listing 5.23: If-Else-ElseIf Example 1

//single selection
if (i > 0)
    Console.WriteLine("The number {0} is positive", i);
//if-then-else selection

if (i > 0)
    Console.WriteLine("The number {0} is positive", i);
else
    Console.WriteLine("The number {0} is not positive", i);

//multicase selection
if (i == 0)
    Console.WriteLine("The number is zero");
else if (i > 0)
    Console.WriteLine("The number {0} is positive", i);
else
    Console.WriteLine("The number {0} is negative", i);

The variable i is the object of evaluation here. The expression in an if statement must resolve to a boolean value type.

// Compiler Error
if (1)
    Console.WriteLine("The if statement executed");
Console.ReadLine();

When the C# compiler compiles the preceding code, it generates the error "Constant value 1 cannot be converted to bool."

Listing 5.24 shows how conditional or (||) and conditional and (&&) operators are used in the same manner.

Listing 5.24: If-Then-Else Example 2

//Leap year
int year = 1974;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
    Console.WriteLine("The year {0} is leap year ", year);
else
    Console.WriteLine("The year {0} is not leap year ", year);

Switch

From the example in Listing 5.25, you can see that the switch statement is similar to an if-else ifelse if-else form of an if statement.

Listing 5.25: Switch Example 1

string
day = "Monday";
Console.WriteLine("enter the day :");
day = Console.ReadLine();

switch (day)
{
    case "Mon":
        break;
    case "Monday":
        Console.WriteLine("day is Monday: go to work");
        break;
    default:
        Console.WriteLine("default");
        break;
}

switch (strVal1)
{
    case "reason1":
        goto case "reason2"; // this is a jump to mimic fall-through
    case "reason2":
        intOption = 2;
        break;
    case "reason 3":
        intOption = 3;
        break;
    case "reason 4":
        intOption = 4;
        break;
    case "reason 5":
        intOption = 5;
        break;
    default:
        intOption = 9;
        break;
}

Do-While

The while loop allows the user to repeat a section of code until a guard condition is met. Listing 5.27 presents a simple while loop designed to find out the number of digits in a given value.

Listing 5.27: While Example

//find out the number of digits in a given number
int i = 123;
int count = 0;
int n = i;

//while loop may execute zero times
while (i > 0)
{
    ++count;
    i = i / 10;
}
Console.WriteLine("Number {0} contains {1} digits.", n, count);

For a given number i = 123, the loop will execute three times. Hence the value of the count is three at the end of the while loop.

This example has one logical flaw. If the value of i is 0, the output of the code will be "Number 0 contains 0 digits." Actually, the number 0 contains one digit. Because the condition of the while loop i > 0 is false from the beginning for the value i = 0, the while loop does not even execute one time and the count will be zero. Listing 5.28 presents a solution.

Listing 5.28: Do Example

//find out the number of digits in a given number
int i = 0;
int count = 0;
int n = i;
do
{
    ++count;
    i = i / 10;
} while (i > 0);
Console.WriteLine("Number {0} contains {1} digits.", n, count);

The do-while construct checks the condition at the end of the loop. Therefore, the do-while loop executes at least once even though the condition to be checked is false from the beginning.

For

The for loop is useful when you know how many times the loop needs to execute. An example of a for statement is presented in Listing 5.29.

Listing 5.29: For Example 1

for
(int i = 0; i < 3; i++)
    a(i) = "test"

for (string strServer = Console.ReadLine();
strServer != "q" && strServer != "quit";
strServer = Console.ReadLine())
{
    Console.WriteLine(strServer);
}

Listing 5.30 shows the use of a for loop with the added functionality of break and continue statements.

//For loop with break and continue statements
for (int i = 0; i < 20; ++i)
{
   if (i == 10)
       break;
   if (i == 5)
       continue;
   Console.WriteLine(i);
}

The output of the code in the listing is as follows:


0
1
2
3
4
6
7
8
9

When i become 5, the loop skips over the remaining statements in the loop and goes back to the post loop action. Thus, 5 is omitted from the output. When i become 10, the program will break out of the loop.

ForEach

The foreach statement allows the iteration of processing over the elements in arrays and collections. Listing 5.31 contains a simple example.

Listing 5.31: ForEach Example 1

//foreach loop
string[] a = { "Chirag", "Bhargav", "Tejas" };
foreach (string b in a)
Console.WriteLine(b);

Within the foreach loop parentheses, the expression consists of two parts separated by the keyword in. To the right of in is the collection, and to the left is the variable with the type identifier matching whatever type the collection returns.

Listing 5.32 presents a slightly more complex version of the foreach loop.

Listing 5.32: ForEach Example 2

Int16
[] intNumbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (Int16 i in intNumbers)
{
   System.Console.WriteLine(i);
}

Each iteration queries the collection for a new value for i. As long as the collection intNumbers returns a value, the value is put into the variable i and the loop will continue. When the collection is fully traversed, the loop will terminate.

GoTo

You can use the goto statement to jump to a specific segment of code, as shown in Listing 5.33. You can also use goto for jumping to switch cases and default labels inside switch blocks. You should avoid the overuse of goto because code becomes difficult to read and maintain if you have many goto jumps within your code.

Listing 5.33: GoTo Example


  label1:
        ;
        //...
        if (x == 0)
            goto label1;
        //...


Break

The break statement, used within for, while, and do-while blocks, causes processing to exit the innermost loop immediately. When a break statement is used, the code jumps to the next line following the loop block, as you'll see in Listing 5.34.

Listing 5.34: Break Example

while
(true)
{
    //...
    if (x == 0)
        break;
    //...
}
Console.WriteLine("break");

Continue

The continue statement (shown in Listing 5.35) is used to jump to the end of the loop immediately and process the next iteration of the loop.

Listing 5.35: Continue Example

int
x = 0;
while (true)
{
    //...
    if (x == 0)
    {
        x = 5;
        continue;
    }
    //...

    if (x == 5)
        Console.WriteLine("continue");
    //...
}

Return

The return statement is used to prematurely return from a method. The return statement can return empty or with a value on the stack, depending upon the return value definition in the method (Listing 5.36 shows both). Void methods do not require a return value. For other functions, you need to return an appropriate value of the type you declared in the method signature.

Listing 5.36: Return Example


void MyFunc1()
{
// ...
if(x == 1)
return;
// ...
}

int MyFunc2()
{
// ...
if(x == 2)
return 1919;
// ...
}

Conclusion

Hope this article would have helped you in understanding control statements in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.


Login to add your contents and source code to this article
 About the author
 
Puran Mehra

Working as a Software professional. 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.