C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !






Flow Control in C#


Posted Date: 15 Aug 2008    Resource Type: Articles    Category: General
Author: Gaurav AroraMember Level: Gold    
Rating: Points: 15



Scope: Scope of this artcile is upto its title and descriptive to its practical scenario.

Flow Control


This contains:

Conditional statements:


As it predicts from name that using these statement we can group our code depends on certain conditions. These are mainly if and switch statements.


  • The if statement

  • if statement comes with many roles like if .. else, if . else if, if .. else if . else etc. The following program tells the whole story:/p>


    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : gaurav.aroraose@yahoo.co.in*/


    // File name : conditionalstatementif.cs

    using System;

    namespace CSharp.AStepAhead.conditionalstatementif
    {
    class conditionalstatementif
    {
    public static string str;

    int i = 10;

    static void Main()
    {
    Console.WriteLine("Enter Some text : ");
    str = Console.ReadLine();
    Console.WriteLine("\nThis is single if statement");
    if (str.Length == 0)
    Console.WriteLine("You have entered : {0}", str);
    Console.ReadLine(); //this is out-side if block

    Console.WriteLine("\nThis is if multiple statements");
    if (str.Length == 0)
    {
    str = "nothing";
    Console.WriteLine("You have entered : {0}", str);
    }
    if (str == "nothing")
    str = "";
    Console.WriteLine("\nThis is multiple if statement");
    if (str.Length != 0)
    {
    if (str.Length == 1)
    Console.WriteLine("You have entered : {0} only one character", str);

    else if (str.Length > 2)
    Console.WriteLine("You have entered : {0} more than one characters", str);

    }
    else
    Console.WriteLine("You have entered an empty string");
    }
    }
    }


  • The switch statement

    The switch . case statement is good when we have lot of grouped conditions. Lets check the followings:



    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : gaurav.aroraose@yahoo.co.in*/


    // File name : conditionalstatementswitchcase.cs

    using System;

    namespace CSharp.AStepAhead.conditionalstatementswitchcase
    {

    class conditionalstatementswitchcase
    {
    public static int num;
    static void Main()
    {
    Console.WriteLine("Enter Number(s) only [0-9]: ");
    num = int.Parse(Console.ReadLine());

    switch (num)
    {
    case 1:
    Console.WriteLine("\nYou have entered Number - One");
    break;
    case 2:
    Console.WriteLine("\nYou have entered Number - Two");
    break;
    case 3:
    Console.WriteLine("\nYou have entered Number - Three");
    break;
    case 4:
    Console.WriteLine("\nYou have entered Number - Four");
    break;
    case 5:
    Console.WriteLine("\nYou have entered Number - Five");
    break;
    case 6:
    Console.WriteLine("\nYou have entered Number - Six");
    break;
    case 7:
    Console.WriteLine("\nYou have entered Number - Seven");
    break;
    case 8:
    Console.WriteLine("\nYou have entered Number - Eight");
    break;
    case 9:
    Console.WriteLine("\nYou have entered Number - Nine");
    break;
    default:
    Console.WriteLine("\nSorry you have entered invald number");
    break;
    }

    }
    }
    }



Iterations:


C# provides four iterative blocks [for, while, do . . . while, foreach] with the help of these you can do repetitive tasks.


  • The for Loop

  • The for loop is the big one loop which allow you to iterate or repeat the task by specifying the condition.
    Syntax: for (starter; conditioner; iterator) { statement (s);}




    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : gaurav.aroraose@yahoo.co.in*/


    // File name : iterationfor.cs

    using System;

    namespace CSharp.AStepAhead.iterationfor
    {

    class iterationfor
    {
    public static string str;
    static void Main()
    {
    Console.WriteLine("Enter Some text : ");
    str = Console.ReadLine();
    string str1=str.ToLower();
    char c;
    int vowel =0, consonent=0;

    for (int i=0; i <= str1.Length - 1; i++)
    {
    //Cont for vowels
    c = Convert.ToChar(str1.Substring(i, 1));

    if ((c == 'a') ||( c == 'e' )|| (c == 'i') ||( c == 'o') ||( c == 'u'))
    vowel++;
    else
    consonent++;
    }
    Console.WriteLine("String \"{0}\", Contains:{1} Vowels and {2} Consonent", str, vowel, consonent);
    Console.ReadLine();
    }
    }
    }


  • The While Loop

  • The While loop is has the great skill to test before iterate. The programmers of C++ and Java already aware from the working of While loop, its also the same as While . Wend loop in Visual Basic. So, no need to get bore to learn this new loop.
    Syntax: while (condition) { statement (s);}

    In the following example, we just try to check the power of this loop, as we know this will check the condition first which is almost false to check. We will just find what the user entered as plain text and then display the same text with count of characters, you will not one thing, I have applied here [\b] escape sequence to remove the last character. We will get another example to solve the same with other type or method later on.


    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : gaurav.aroraose@yahoo.co.in*/


    // File name : iterationwhile.cs

    using System;

    namespace CSharp.AStepAhead.iterationwhile
    {

    class iterationwhile
    {
    public static string str;
    public static char c;
    static void Main()
    {
    Console.WriteLine("Enter Some text [x-Exit]: ");
    int i=0;
    while (c != 'x')
    {
    c = (char)Console.Read();
    i += (c!=' ' ? 1 : 0);
    str += c;
    }

    Console.WriteLine("You have Entered Text \"{0}\b\", Contains:{1} character(s) and Total Length is :{2} Character(s)", str,i-1,str.Length-1);
    Console.ReadLine();
    }
    }
    }


  • The do . . while Loop

  • The do . while loop is similar to do .. while in C++ and Java also to Loop.While in Visual basic. In this the block is executed first and then checks the condition. So, then block is executed at once if the condition is false.
    Syntax: do{ statement (s);} while (condition);




    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : gaurav.aroraose@yahoo.co.in*/


    // File name : iterationdowhile.cs

    using System;

    namespace CSharp.AStepAhead.iterationdowhile
    {

    class iterationdowhile
    {
    static void Main()
    {
    int i = 0;
    do
    {
    Console.WriteLine("This statement Execute atleast once");
    Console.WriteLine("\nThe Value of i: {0}", i);
    i++;
    Console.WriteLine("\nThe Value of i: {0}", i);
    } while (i != 1);
    Console.ReadLine();
    }
    }
    }


  • The foreach Loop

  • The foreach is newly added to C# which is not presented in C++, actually this is borrowed from loops of Visual Basic. This has very great ability to iterate through the each element in a collection.




    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : gaurav.aroraose@yahoo.co.in*/


    // File name : iterationdoforeach.cs

    using System;

    namespace CSharp.AStepAhead.iterationdoforeach
    {

    class iterationdoforeach
    {
    static void Main()
    {

    // cs_foreach.cs
    int[] intArray = new int[] { 0, 1, 8, 3, 4, 5, 16 };
    Console.WriteLine("Array intAray contains : \n");
    foreach (int i in intArray)
    {
    Console.WriteLine(i);
    }
    Console.Read();
    }
    }
    }














    For more details, visit http://www.msdotnetheaven.com/ChaptersCsharp/csharplanguagei.htm




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Interviews  .  Flow control in C#  .  Flow control  .  C# Syntax  .  C# flow control  .  Article  .  .net  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: C#:Operators
Previous Resource: Jump Statement(s),Enumerations, Arrays, ArrayList
Return to Discussion Resource Index
Post New Resource
Category: General


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design


Contact Us    Privacy Policy    Terms Of Use