Nov 21, 2009

Lesson #2 - Switch Statement In C# - Using the Switch Statement in C#

free web hosting
Open Discussion & Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > .NET (VB, C# & J#)

Lesson #2 - Switch Statement In C# - Using the Switch Statement in C#

oval
In the previous lesson we demonstrated did a basic input output application which asked your your name and replied with a general greeting using the name you entered.

In this lesson we are going to learn about a conditional statement called the switch statement. Usually if and if else [color=#3333FF]statements are taught before switch statements. Although these are very useful, I find the switch to be easier and more fun to use.

The program written below is very similar to the previous program where the user is asked to enter their name, however now the program will look for four distinct string values and ti will generate output according to the string entered. Here are the things to observe when reading and replicating this program.

1.) 2 string variables are declared (greeting and fullName)
2.) A value is assigned using our Console.ReadLine() method. (Point where we insert the value.)
3.) the value of the variable greeting depends on the value entered for the variable fullName
4.) The program is case sensitive. Basically this is because different case letters have different values. So a lower case t will not evaluate the same as an upper case T. So ulitmately what does this mean. Well let's if you entered george bush as opposed to George Bush, you would get the default greeting because the program would not recognize your lower case entry of george bush as George Bush. If it does not make sense, run the program and change the case. You will see what I mean.
5.) Lastly, the default option is included in the case statement for the instances where neither of the output meets any of the criteria of the case statement.

With that said let's look at the code, replicate it and modify it to your liking.

CODE


using System;

namespace ConsoleApplication
{
    /// <summary>
    /// Testing out the case Statement
    /// </summary>
    class switchStatement
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            string fullName, greeting;
            

            Console.Write("Please enter your name: ");
            fullName = Console.ReadLine();

            switch (fullName)
            {
                case "YOUR NAME HERE":
                    greeting = "You are the best!!";
                    break;
                case "Bill Gates":
                    greeting = "You are super wealthy!";
                    break;
                case "George Bush":
                    greeting = "hmmm????";
                    break;
                case "Kenneth Lay":
                    greeting = "How is Court Going?";
                    break;
                default:
                    greeting = "I'm sorry I did not recognize you!";
                    break;
            }//end switch statement

            Console.WriteLine();
            Console.WriteLine(greeting);
            Console.WriteLine();
            Console.WriteLine("Press [ENTER] to Exit");
            Console.ReadLine();


        }//end Main
    }//end class "switchStatement
}//end namespace





As I might have mentioned on my previous post I am using Visual Studio. I believe the Express version is out on the web for free. However you might need to install NetFramework before you proceed to install VS.

Also, just like the previous program, an adobe file will be attached with the source code. variables and comments are all color coded.

oval

 

 

 


Comment/Reply (w/o sign-up)

iGuest-Alishia Johnson
Computer Programming
Lesson #2 - Switch Statement In C#

Why might a programmer choose one of these two types of statements(if else and switch)over the other? When is one better than the other?

-reply by Alishia Johnson

Comment/Reply (w/o sign-up)

(G)frostbite
Computer Programming
Lesson #2 - Switch Statement In C#

Apart from the cleaner construct of the switch, in C#, the if, else if, else if construct is actually embedded if statements which is less optimal especially if you are dealing with very deep nests.

On the other hand the if else construct gives you greater flexibility on each of your conditional phrase.

-reply by frostbite

Comment/Reply (w/o sign-up)

(G)kushal
what does the following program print?
Lesson #2 - Switch Statement In C#

#include <stdio.H>

int main (void)

{

int x=97;

int I; 

for(I=8, I<10; I++)

   {

   if(I%2==0)

      x--;

   else

      x++;

   }

   switch(x)

   {

         case 94: printf("94\and");

         case 95: printf("95\and");

         case 96: printf("96\and");

         case 97: printf("97\and");

         case 98: printf("98\and");

         case 99: printf("99\and");

   }

}

-reply by kushal

 

 

 


Comment/Reply (w/o sign-up)


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : lesson, 2, switch, statement, c, switch, statement, c

  1. C# Tutorial : Lesson 9 - Constructors & Destructors
    (0)
  2. C# Tutorial : Lesson 8 - Functions/methods
    (0)
    The programming model has gone through many refinements, each change improving upon the model. One
    of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these
    are fragments of code within a program. They offer the following advantages:- Reduction of code
    duplication by offering re-usability Simplifying program logic by decomposing the program into
    smaller blocks Improving readability of the program Why do we need functions?
    Consider the following program:- CODE using System; namespace ConsoleApplication1 { ....
  3. C# Tutorial : Lesson 7 - Creating Value Types & Reference Types - Part II
    (2)
    foreach statement This statement is explicitly used to traverse through arrays. The
    benefit of using foreach over the normal for statement is that it is not needed to check the
    size of the array while using the former. Syntax:- foreach(type identifier in expression) {
    statement 1; statement 2; .... } Suppose we have an array StudentNames containing the name of all
    the students in a class. We need to display the name of each one of them on screen. First we will
    see how it can be done using the for loop. CODE string StudentNames = new string {"....
  4. C# Tutorial : Lesson 6 - Creating Value Types & Reference Types - Part I
    (0)
    Value Types & Reference Types In C#, Variables are either value types or reference types
    depending on what they store, values or references. By reference we imply that the variable holds
    the memory address of another location where the actual value is stored. All built in data types -
    Int, Char, String, Float, Boolean, etc are value types while classes are reference types. The
    following is a diagrammatic representation of these two types. In this picture there are two
    variables Num1 and Num2. Both of these being integer variables store the values directly.....
  5. C# Tutorial : Lesson 5 - Encapsulation & Abstraction
    (0)
    Encapsulation & Abstraction Two concepts that go together in the object oriented approach
    are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of
    an object, while Encapsulation is the hiding of the non-essential features. Think of a person
    driving a car. He does not need to know the internal working of the engine or the way gear changes
    work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much
    turning the steering wheel needs, etc (Abstraction). Consider the example from ....
  6. C# Tutorial : Lesson 4 - Object Oriented Programming
    (3)
    Object Oriented Programming Object Oriented Programming is a methodology modeled on real
    life. It comprises of the basic unit, an object, being used in implementing a program. Think of all
    the objects around you - cars, buses, birds, trees, etc. You will find countless ones of them,
    everywhere you go. In order to tackle this huge number, we started classifying them, thus came the
    term Class. Class A class is a composition of the theoretic characteristics (attributes and
    properties) of an object and the things it can do - behaviors, methods and features. Tak....
  7. C# Tutorial : Lesson 3 - Programming Constructs
    (1)
    Conditional Branching By branching we imply, having different paths for execution.
    Conditions are used to determine which statements need to be executed. Suppose, you have a program
    to store the details of employees. Depending upon the post of the employee, there would be various
    fields associated with it. A department head, for example, would have a property denoting the
    department he heads, etc. We use conditional branching in such a scenario. C# provides the
    following conditional constructs:- if .. else Syntax:- if ( ) { statements } else { statement....
  8. C# Tutorial : Lesson 2 - Variables & Operators
    (0)
    Variables A Variable is a named location that stores a value. Although variables are
    physically stored in the RAM, their actual memory address is not known to the programmer. We can use
    the variables via the name we give them. These are the rules for naming a variable:- The name must
    begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9)
    or underscore (_) Special Characters such as ? - + * / \ ! @ # $ % ^ ( ) { } , ; : . cannot be
    used in the variable name. A variable name must not be the same as a reserved k....
  9. C# Tutorial : Lesson 1 - Hello World Program
    (0)
    This is the first installment of my venture to explain the bits and pieces of C# that I have managed
    to learn at NIIT. In this lesson we would be creating the Hello World application. STEP 1 : Create
    a New Console Application in Visual C# The IDE automatically adds the following code:- CODE
    using System; using System.Collections.Generic; using System.Text; namespace HelloWorld {
        class Program     {         static void Main(string args)         {         }     } } Lets
    take a look at the first 3 lines. All of these lines begin with the keyword using....
  10. Lesson #3 - Basic Math Operators And Random #s
    Lesson #3 - Basic Math Operators and Random #s (0)
    In this lesson I will cover how to use basic math operations, well addition really but you can also
    use subtraction , division and multiplication . I would also like to note that when doing
    division, if variabes of int type are used you will not get any remainders (i.e. n.345984). To be
    able to work with real numbers, numbers with decimals, you can use float. Below is a way to declare
    a float and assign it a value: float floatNumber; float Number = 28.47f; Aside from
    generating random numbers and basic math operations, we will also incorporate an if statement a....
  11. Lesson #1 - Introduction To C#
    Console Application (1)
    This tutorial will help get you started with C# Sharp. These tutorials will assume that you are
    using the Visual Studio environment. If you are just curious to test out some code, then you can
    copy and paste this code into your CS file, however, before doing so, make sure to name your project
    the same as the namespace on the code. But since this first program is fairly easy, it will not
    hurt to type it out. It is fairly easy and short. Also, this program is highly commented so it
    should be easy to follow along. Comments will have 2 forward slashes before them '....
  12. VB.NET: Switch Regional Language Automatically
    When the field being edited gets FOCUS (2)
    Switch the language of the Textbox Control automatically upon receiving focus Hi guys,     This
    tutorial sparked off from my own ventures to incorporate a particular feature in my own software -
    which uses mixed language (English & Thai) on a couple of screens to store user data. Certain
    fields, apart from First & Last Names & parts of address were to be entered in Thai. Now the current
    language can be easily switched by pressing Alt-Left Shift (or whatever key combination you've
    set your system to) - but when you consider the same key-combination has to be re....

    1. Looking for lesson, 2, switch, statement, c, switch, statement, c

See Also,

*SIMILAR VIDEOS*
Searching Video's for lesson, 2, switch, statement, c, switch, statement, c
advertisement



Lesson #2 - Switch Statement In C# - Using the Switch Statement in C#

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com