Chapter 4 � Control Structures Part 1

Document Sample
Chapter 4 � Control Structures Part 1 Powered By Docstoc
					        Program Modules in C#
       Modules
         Class
         Method
       The .NET Framework Class Library (FCL)
         Helps to increase reusability
         Console
         MessageBox
         Math calculations, character and string
          manipulations, I/O operations, error
          checking
1
        Math Class Methods
       Class Math is located in namespace System
        (not necessary to add an assembly reference)
       Using methods
           ClassName.MethodName( argument1, arument2, … )
           Example: Math.Sqrt (900.0)
           List of methods are in text
             • Abs, Ceiling, Cos, Exp, Floor, Log, Max, Min, Pow, Sin,
               Sqrt, Tan
       Constants
           Math.PI = 3.1415926535…
           Math.E = 2.7182818285…
2
        Methods
       Variables
         Declared in a method = local variables
         Declared outside a method = global
          variables
       Reasons for using Methods
         “Divide and conquer”  Decomposition
         Cut down on repetition
         Reusability

3
        Method Definitions
       Writing a custom method
         Header and Body same as in C++
         All methods must be defined inside of a
          class
         Methods can return at most one value!!!




4
        More I/O
       Until now
         Input from Console
         Output to Console or MessageBox
         These can only handle one input or output
          value at a time
       Next
         Attaching multiple GUI components to an
          application and event handling
         Button GUI component
5           • Requires an event handler
    Instantiation of
    SquareIntForm

6
       Destructor




    InitializeComponent
    method in this
    generated code –
    defines non-default
    properties for
    components on form




7
// SquareIntForm.cs
   // A programmer-defined Square method.                       Start of class SquareInt.
                                                                It implements a Form
   using   System;                  //   includes basic data types
   using   System.Drawing;          //   for graphics capabilities
   using   System.Collections;      //   for complex data structures
   using   System.ComponentModel;   //   controls component behavior
   using   System.Windows.Forms;    //   for GUI development
   using   System.Data;             //   for reading outside data


  namespace SquareInt
 {
    // form used to display results of squaring 10 numbers
    public partial class SquareIntForm : Form
    {
        public SquareIntForm()                   Constructor
        {
            InitializeComponent();
        }
    // Square method definition          The Square method. Receives one
   int Square( int y )                   integer and returns an integer
   {
        return y * y; // return square of y
   } // end method Square                   Double-click on button to generate
                                            this event handler. Code it.
   private void calculateButton_Click (object sender,
       System.EventArgs e)
   {                                     ReInit for each button click!
        outputLabel.Text = "";

       // loop 10 times
       for ( int counter = 1; counter <= 10; counter++ )
       {
          // calculate square of counter and store in result
          result = Square( counter );

          // append result to output string
          outputLabel.Text += "The square of " + counter +
               " is " + result + "\n";
        }
     } // end calculateButton_Click
  } // end of class SquareInt
} // end namespace
// MaximumValue.Designer.cs                              Prompts for Text
+     Windows Form Designer generated code               Boxes



     private   System.Windows.Forms.Label firstNumberLabel;
     private   System.Windows.Forms.Label secondNumberLabel;
     private   System.Windows.Forms.Label thirdNumberLabel;
     private   System.Windows.Forms.Label maximumLabel;
     private   System.Windows.Forms.TextBox firstNumberTextBox;
     private   System.Windows.Forms.TextBox secondNumberTextBox;
     private   System.Windows.Forms.TextBox thirdNumberTextBox;
     private   System.Windows.Forms.Button calculateButton;
                                                       Input values in Text
                                                       Boxes
// MaximumValueForm.cs
// Finding the maximum of three double values.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;


// Method Maximum uses method Math.Max to determine the
// maximum value among the three double arguments
double Maximum( double x, double y, double z )
{
    return Math.Max( x, Math.Max( y, z ) );
}
                                                 The use of Math.Max uses the
                                                 Max method in class Math. The
                                                 dot operator is used to call it.
  // get the floating-point values that the user entered and
  // invoke method Maximum to determine the maximum value
  private void calculateButton_Click (object sender,
    System.EventArgs e)                               Gets input from Text
  {                                                   Boxes when button clicked
       // get inputted values and convert strings to doubles
        double number1 =
            Double.Parse( firstNumberTextBox.Text );

        double number2 =
           Double.Parse( secondNumberTextBox.Text );

        double number3 =
           Double.Parse( thirdNumberTextBox.Text );

        // invoke method Maximum to determine the largest value
        double maximum = Maximum( number1, number2, number3 );

        // display maximum value
        maximumLabel.Text = "maximum is: " + maximum;

    }   // end method calculateButton_Click                 Displays output in
  } // end class MaximumValue                               Label

} // end namespace MaximumValue
         Calling Methods
        Three ways to call methods
            Method name itself
                Square (x)
                Maximum (num1, num2, num3)
            Reference to an object following by the dot
             operator and the method name
                 string1.CompareTo (string2)
            Class name followed by dot and method
             name (static method)
                 Math.Max( y, z )
13
         Argument Promotion
        Implicit Conversion
            Only done if no data will be lost
            Coercion of arguments to methods and in mixed-
             type expressions to a higher type
        Explicit Conversion
            Done with cast or class Convert in namespace
             System
              • Widening - Make an object that of a derived
                class and more complex
              • Narrowing - Make an object that of a base class
                and cause some data loss
14
            Cast Example: int result = Square ( (int ) y );
                C# Namespaces
      FCL is composed of namespaces
      A namespace is a group of classes and their
       methods
      Namespaces are stored in .dll files called
       assemblies
      Included in a program with the using keyword
            System.Console.WriteLine  Console.WriteLine

      Must add a reference to appropriate assembly
       (except for namespace System)
      FCL includes many names (look up “.NET Framework,
15
         class library” in the help doc)
     C# Namespaces in FCL
Namespace          Description
System             Contains essential classes and data types
                   (such as int, double, char, etc.).
                   Implicitly referenced by all C# programs.
System.Data        Contains classes that form ADO .NET, used
                   for database access and manipulation.
System.Drawing     Contains classes used for drawing and
                   graphics.
System.IO          Contains classes for the input and output of
                   data, such as with files.
System.Threading   Contains classes for multithreading, used to
                   run multiple parts of a program
                   simultaneously.

     16
         Value Types and Reference Types

        Value types
            Contains data of the specified type
            Built in
            Programmer created - structs and
             enumerations
        Reference types
            Contain an address
            Built-in (string and object)
            Programmer created - Classes and Interfaces and
             Delegates
17          All values are 32bit allowing cross-platform use
         Passing Arguments: Call-By-Value
         vs. Call-By-Reference
        Value types are passed by value and
         reference types are passed by reference

        To pass a value type by reference?
            The ref keyword specifies by-reference
              • can modify original variable
              • used with variables already initialized
            The out keyword means a called method
             will initialize it
18
9    // x is passed as a ref int (original value will change)
10   static void SquareRef( ref int x )
11   {                                   When passing a value by
12      x = x * x;                       reference the value will be altered
13   }                                   in the rest of the program as well
14
15   // original value can be changed        and initialized
16   static void SquareOut( out int x        )
17   {
18      x = 6;                               Since x is passed as out the variable
19      x = x * x;                           can then be initialed in the method
20   }
21
22   // x is passed by value (original value not changed)
23   static void Square( int x )
24   {
                               Since not specified, this value is defaulted to
25      x = x * x;             being passed by value. The value of x will not be
26   }                         changed elsewhere in the program because a
                               duplicate of the variable is created.
            Random Number Generation
    Class Random within namespace System
      Numbers are generated using an equation with
       a seed - usually the exact time of day
      randomObject.Next()
         • Returns a number from 0 to Int32.MaxValue
             • Int32.MaxValue = 2,147,483,647
        randomObject.Next( x )
         • Returns a value from 0 up to but not including x
        randomObject.Next( x, y )
         • Returns a value between x and up to but not including y
20
// Different RandomIntForm.cs
// Random integers.
using System;
using System.Windows.Forms;

// calculates and displays 20 random integers
public partial class RandomIntForm : Form
{
   // main entry point for application
   public RandomIntForm ()
   { InitializeComponent ();                                   Creates a new Random object
      int value;
      string output = "";

    Random randomInteger = new Random();
      // loop 20 times
      for ( int i = 1; i <= 20; i++ )
                                                            Will set value to a random number
      {                                                     from1 up to but not including 7
         // pick random integer between 1 and 6

        value = randomInteger.Next( 1, 7 );
         output += value + " "; // append value to output

         // if counter divisible by 5, append newline
         if ( i % 5 == 0 )
            output += "\n";                                    Format the output to only
      } // end for structure                                   have 5 numbers per line
  MessageBox.Show( output, "20 Random Numbers from 1 to 6",
        MessageBoxButtons.OK, MessageBoxIcon.Information );

 } // end RandomIntForm constructor
} // end class RandomIntForm

                                  Display the output in a message box
RollDie.cs - Rolling 4 dice.
// THE AUTO GENERATED CODE for the application RollDie
   private System.ComponentModel.Container components = null;
   private    System.Windows.Forms.Button rollButton;
   private    System.Windows.Forms.Label dieLabel1;
   private    System.Windows.Forms.Label dieLabel2;
   private    System.Windows.Forms.Label dieLabel3;
   private    System.Windows.Forms.Label dieLabel4;

// RollDie.cs: Rolling 4 dice.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
 using System.IO;         // enables reading data from files
24
 // form simulates the rolling of 4 dice, and displays them
 public partial class RollDieForm : Form
 {
   private Random randomNumber = new Random();

    public RollDieForm()
    {
       InitializeComponent();
    }
    // method called when rollButton clicked, passes labels to another method
    protected void   rollButton_Click(     object sender, System.EventArgs e )
    {
        // pass the labels to a method that will
        // randomly assign a face to each die
        DisplayDie( dieLabel1 );
                                              Pass the labels to be assigned data
       DisplayDie( dieLabel2 );
       DisplayDie( dieLabel3 );
       DisplayDie( dieLabel4 );
    } // end rollButton_Click

    // determines image to be displayed by current die
    public void DisplayDie( Label dieLabel )
    {                                                              Will return a random
           int face = 1 + randomNumber.Next( 6 );                  integer from 0 up to 6

        // displays image specified by filename
        dieLabel.Image =
           Image.FromFile(Directory.GetCurrentDirectory() +
           "\\images\\die" + face +".gif" );
}
      private   System.Windows.Forms.Button rollButton;
      private   System.Windows.Forms.RichTextBox displayTextBox;
      private   System.Windows.Forms.Label dieLabel1;
       :
      private   System.Windows.Forms.Label dieLabel12;

// RollDie2Form.cs: Rolling 12 dice with frequency chart.

// displays the different dice and frequency information
public partial class RollDie2Form : Form
{
  private Random randomNumber = new Random();
  private int ones, twos, threes, fours, fives, sixes;

     public RollDie2Form()
     {
                                                  Sets all of the variables to 0
         InitializeComponent();
         ones = twos = threes = fours = fives = sixes = 0;
 }
// simulates roll by calling DisplayDie for    each label and displaying the results
protected void rollButton_Click( object sender, System.EventArgs e )
{
   // pass labels to a method that randomly assigns a face to die
    DisplayDie( dieLabel1 );
    :
                                              Pass the label to be
    DisplayDie( dieLabel12 );                 assigned a random
                                              number

   double total = ones + twos + threes + fours + fives + sixes;
   // display the current frequency values
   displayTextBox.Text = "Face\t\tFrequency\tPercent\n1\t\t" +
      ones + "\t\t" +
      String.Format( "{0:F2}", ones / total * 100 ) +
      "%\n2\t\t" + twos + "\t\t" +
      String.Format( "{0:F2}", twos / total * 100 ) +
      "%\n3\t\t" + threes + "\t\t" +
      String.Format( "{0:F2}", threes / total * 100 ) +
      "%\n4\t\t" + fours + "\t\t" +
      String.Format( "{0:F2}", fours / total * 100 ) +
      "%\n5\t\t" + fives + "\t\t" +
      String.Format( "{0:F2}", fives / total * 100 ) +
      "%\n6\t\t" + sixes + "\t\t" +
      String.Format( "{0:F2}", sixes / total * 100 ) + "%";
} // end rollButton_Click

// display the current die, and modify frequency values
public void DisplayDie( Label dieLabel )
{                                             Assign a random face to the
   int face = 1 + randomNumber.Next( 6 );     label based on the number
   dieLabel.Image = Image.FromFile(           generated
    Directory.GetCurrentDirectory() + "\\images\\die" + face + ".gif“ );
          // add one to frequency of current face
          switch ( face )
          {
             case 1: ones++;
                break;           A switch statement is used to keep
0            case 2: twos++;     track of number of each die rolled
1               break;
3            case 3: threes++;
4               break;
6            case 4: fours++;
7               break;
9            case 5: fives++;
0               break;
2            case 6: sixes++;
3               break;
5         } // end switch
    } // end DisplayDie
        12 labels




A button with a click event




         DisplayTextBox
           Example:
           Game of Chance

    GUI controls
        GroupBox
         • Holds other
           controls
         • Manages and
           organizes them
        PictureBox
         • Used to display
           a picture on the
           form
32
 private System.ComponentModel.Container components = null;


  private   System.Windows.Forms.PictureBox     imgPointDie1;
  private   System.Windows.Forms.PictureBox     imgPointDie2;
  private   System.Windows.Forms.PictureBox     imgDie2;
  private   System.Windows.Forms.PictureBox     imgDie1;

  private System.Windows.Forms.Label lblStatus;

  private System.Windows.Forms.Button rollButton;
  private System.Windows.Forms.Button playButton;

  private System.Windows.Forms.GroupBox fraPoint;



// CrapsGameForm.cs
public partial class CrapsGameForm : Form
{


    // declare other variables
    int myPoint;
    int myDie1;
    int myDie2;
                            Global variables
public enum DiceNames
 {
                                Creates an enumeration of the
         SNAKE_EYES = 2,        constant values in craps
         TREY = 3,
         CRAPS = 7,
         YO_LEVEN = 11,
         BOX_CARS = 12,
 }
// simulate next roll and result of that roll
protected void rollButton_Click(
   object sender, System.EventArgs e )
{
   int sum;
                                  When the second rolled sum equals
     sum = rollDice();            the first rolled sum the player wins

     if ( sum == myPoint )
     {
          lblStatus.Text = "You Win!!!";
          rollButton.Enabled = false;
          playButton.Enabled = true;
     }
      else
         if ( sum == ( int )DiceNames.CRAPS )
         {
             lblStatus.Text = "Sorry. You lose.";   Casting enum type to an int using
              rollButton.Enabled = false;           explicit conversion
             playButton.Enabled = true;
         }

} // end rollButton_Click

// simulate first roll and result of that roll
protected void playButton_Click(object sender, System.EventArgs e )
{
    int sum;
    myPoint = 0;
     fraPoint.Text = "Point";
    lblStatus.Text = "";
    imgPointDie1.Image = null;
    imgPointDie2.Image = null;

    sum = rollDice();
  switch ( sum )
  {                                            If on the first roll the players
     case ( int )DiceNames.CRAPS:              gets a 7 or an 11 they win
     case ( int )DiceNames.YO_LEVEN:
        rollButton.Enabled = false;      // disable Roll button
        lblStatus.Text = "You Win!!!";
        break;
     case ( int )DiceNames.SNAKE_EYES:
     case ( int )DiceNames.TREY:                 If the first roll is a 2, 3 or 12,
     case ( int )DiceNames.BOX_CARS:             the player loses.
        rollButton.Enabled = false;
        lblStatus.Text = "Sorry. You lose.";
        break;
     default:
        myPoint = sum;                         Any other number allows the
        fraPoint.Text = "Point is " + sum;     player to roll again
        lblStatus.Text = "Roll Again";
         displayDie( imgPointDie1, myDie1 );
        displayDie( imgPointDie2, myDie2 );
        playButton.Enabled = false;
        rollButton.Enabled = true;
        break;
   } // end switch
} // end playButton_Click
// simulates the rolling of two dice
private int rollDice()
{
    int die1, die2, dieSum;
    Random randomNumber = new Random();

    die1 = randomNumber.Next( 1, 7 );
    die2 = randomNumber.Next( 1, 7 );     Generates two random
                                          numbers, one for each die
    displayDie( imgDie1, die1 );
    displayDie( imgDie2, die2 );

    myDie1   = die1;
    myDie2   = die2;
    dieSum   = die1 + die2;
    return   dieSum;

} // end rollDice
CrapsGame.cs Program Output
         Duration of Identifiers
        Duration
            The amount of time an identifier exists in memory
        Local variables of a method
            Automatic duration: Created when declared and
             destroyed when the block exits
            Not initialized
        Instance variables of a class
            Initialized by compiler, if not done by programmer
              • Most variables are set to 0, false or null


39
       Scope Rules
      Scope
        Portion of a program in which a variable can be
         accessed
      Class scope
        From when created in class until end of class (})
        Global to all methods in that class
        Repeated names causes previous to be hidden
         until scope ends
      Block scope
        From when created until end of block (})
        Only used within that block
        Cannot repeat variable names
40
// A Scoping example.
 private System.ComponentModel.Container components = null;
 private System.Windows.Forms.Label outputLabel;

 public partial class Scoping : Form
{
  public int x = 1;               This variable has class scope and
                                     can be used by any method in the
   public Scoping()                  class
   {
      InitializeComponent();                              This variable is local only to Scoping.
                                                          It hides the value of the global
                                                          variable
       int x = 5;      // variable local to constructor

       outputLabel.Text = outputLabel.Text +
          "local x in method Scoping is " + x;                  Will output the value of 5

       MethodA();    //   MethodA has automatic local x;
       MethodB();    //   MethodB uses instance variable x
       MethodA();    //   MethodA creates new automatic local x
       MethodB();    //   instance variable x retains its value

       outputLabel.Text = outputLabel.Text +                        Remains 5 despite
          "\n\nlocal x in method Scoping is " + x;                  changes to global version
   }                                                                of x
public void MethodA()
{
   int x = 25;    // initialized each time a is called

  outputLabel.Text = outputLabel.Text +
                                            Uses a new x variable that
     "\n\nlocal x in MethodA is " + x +     hides the value of the
     " after entering MethodA";             global x
  ++x;
  outputLabel.Text = outputLabel.Text +
     "\nlocal x in MethodA is " + x +
     " before exiting MethodA";
}
public void MethodB()
{                                              Uses the global version
                                               of x (1)
   outputLabel.Text = outputLabel.Text +
      "\n\ninstance variable x is " + x +
      " on entering MethodB";
   x *= 10;
   outputLabel.Text = outputLabel.Text +
      "\ninstance varable x is " + x +       Will permanently
      " on exiting MethodB";                 change the value of x
}                                            globally
Scoping.cs
Program Output




43
     Recursion

        Same as C++




44
     Method Overloading

        Methods with the same name
            Can have the same name but need
             different arguments
              • Variables passed must be different
                 • Either in number, type received, or order sent
            Usually perform the same task
              • On different data types



45
      private System.ComponentModel.Container components = null;
      private System.Windows.Forms.Label outputLabel;



// MethodOverloadForm.cs

 public partial class MethodOverloadForm : Form
 {

      public MethodOverloadForm()
      {
         InitializeComponent();


          // call both versions of Square
          outputLabel.Text =
             "The square of integer 7 is " + Square( 7 ) +
             "\nThe square of double 7.5 is " + Square ( 7.5 );
  }

                              Two versions of the square
                              method are called
    // first version, takes one integer
public int Square ( int x )
                                            One method takes
{
                                            an int as
     return x * x;
                                            parameters
}


// second version, takes one double
  public double Square ( double y )
{
     return y * y;
}                                         The other version of the method
                                          uses a double instead of an
                                          integer
// Overloaded methods with identical signatures and different return types.

class MethodOverload2
{

  public int Square( double x )
   {
       return x * x;
                                             This method returns an integer
   }

   // second Square method takes same number, order and type of arguments, error

  public double Square( double y )
   {
       return y * y;
   }
                                              This method returns a double number

                                                             Since the compiler cannot tell
                                                             which method to use based on
                                                             passed values an error is
                                                             generated

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:5
posted:8/9/2012
language:
pages:48