Variants of an else Conditional Statements

The Ternary Operator (?:)

We have already learned what an if...else conditional statement is:

if(condition)
    statement1;
else
    statement2;

Here is an example of such a statement:

double SpecifyFee()
{
    double value;
    string ac = cbxAccountsTypes.Text;

    if(ac == "Residential")
        value = 16.55;
    else
        value = 19.25;

    return value;
}

If you have a condition that can be checked as an if situation with one alternate else, you can use the ternary operator that is a combination of ? and :. Its formula is:

condition ? statement1 : statement2;

The condition would first be checked. If the condition is true, then statement1 would execute. If not, statement2 would execute.

Practical LearningPractical Learning: Using the Ternary Operator

  1. Start Microsoft Visual Studio and, on the Visual Studio 2019 dialog box, click Create a New Project (if you had already started Microsoft Visual Studio, on the main menu, click File -> New -> Project...)
  2. In the list of projects templates, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the project Name to ESCAPE2
  5. Press Enter
  6. Design the form as follows:

    Introduction to Logical Operations

    Control (Name) Text Other Properties
    Label   Eastern Shore Company Associates for Production Entertainment  
    GroupBox   Bill Preparation  
    Label   Account Type:  
    ComboBox cbxAccountsTypes   Items:
    Hospital
    Residential
    Commercial
    Governmentl
    Label   DVR Service:  
    TextBox txtDVRService 0.00 TextAlign: Right
    Label   Sports Package:  
    TextBox txtSportsPackage 0.00 TextAlign: Right
    Label   Sports Package: TextAlign: Right
    TextBox txtSportsPackage   TextAlign: Right
    Button btnEvaluate Evaluate Bill  
    GroupBox   Bill Summary  
    Label   Package Fee:  
    TextBox txtPackageFee 0.00 TextAlign: Right
    Label   Local Taxes:  
    TextBox txtLocalTaxes   TextAlign: Right
    Label   Sub-Total:  
    TextBox txtSubTotal   TextAlign: Right
    Label   State Taxes:  
    TextBox txtStateTaxes   TextAlign: Right
    Label   FCC Fee:  
    TextBox txtFCCFee   TextAlign: Right
    Label   Amount Due:  
    TextBox txtAmountDue   TextAlign: Right
  7. Double-click the Evaluate Bill button
  8. Right-click inside the Code Editor and click Remove and Sort Usings
  9. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace ESCAPE2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void Summarize(double fee, double st, double fcc, double tax1, double tax2)
            {
                txtPackageFee.Text = fee.ToString("F");
                txtSubTotal.Text = st.ToString("F");
                txtFCCFee.Text = fcc.ToString("F");
                txtLocalTaxes.Text = tax1.ToString("F");
                txtStateTaxes.Text = tax2.ToString("F");
                txtAmountDue.Text = (st + fcc + tax1 + tax2).ToString("F");
    
                return;
            }
    
            private void btnEvaluate_Click(object sender, EventArgs e)
            {
                double packageFee;
                string ac = cbxAccountsTypes.Text;
    
                /* if (ac == "Residential")
                    packageFee = 16.85;
                else
                    packageFee = 21.05; */
    
                packageFee = (ac == "Residential") ? 16.85 : 21.05;
    
                double dvr = double.Parse(txtDVRService.Text);
                double sport = double.Parse(txtSportsPackage.Text);
    
                double subTotal = packageFee + dvr + sport;
                double fcc = subTotal * 0.00250881;
                double local = (subTotal + fcc) * 0.0372668;
                double state = (subTotal + fcc) * 0.0082493;
    
                Summarize(packageFee, subTotal, fcc, local, state);
                return;
            }
        }
    }
  10. To execute the project, press Ctrl + F5

    Introducing if...else Conditions

  11. Click the Evaluate Bill button:

    Introducing if...else Conditions

  12. Change the following values:
    Account Type:   Hospital
    DVR Service:    6.75
    Sports Package: 0.00

    Introducing if...else Conditions

  13. Click the Evaluate Bill button:

    Introducing if...else Conditions

  14. Make the following changes:
    Account Type:   Residential
    DVR Service:    0.00
    Sports Package: 9.25
  15. Click the Evaluate Bill button:

    Introducing if...else Conditions

  16. Close the form and return to your programming environment
  17. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  18. In the list of projects templates, click Windows Forms App (.NET Framework)
  19. Click Next
  20. Change the project Name to PayrollEvaluation04
  21. Press Enter
  22. In the Solution Explorer, right-click Form1 -> Rename
  23. Type StocksProcessing (to get StocksProcessing.cs) and press Enter
  24. Read the message box and click Yes
  25. Design the form as follows:

    Topics on the if...else Conditional Statements

    Control (Name) Text
    Label   Taxable Gross Income:
    TextBox txtTaxableGrossIncome
    Button btnCalculate Calculate
    Label   Income Tax:
    TextBox txtIncomeTax
    Label   Net Pay:
    TextBox txtNetPay
  26. Double-click the Calculate button

if...else if and if...else

If you use an if...else situation, you can process only two statements. In some cases, you may deal with more than two conditions. In this case, you can use an if...else if condition. Its formula is:

if(condition1) statement1;
else if(condition2) statement2;

If you want, you can add a body delimited by curly brackets, as follows:

if(condition1) {
    statement1;
}
else if(condition2) {
    statement2;
}

The first condition, condition1, would first be checked. If condition1 is true, then statement1 would execute. If condition1 is false, then condition2 would be checked. If condition2 is true, then statement2 would execute. Any other result would be ignored.

Because there can be other alternatives, the C# language provides an alternate else condition as the last resort. Its formula is:

if(condition1)
    statement1;
else if(condition2)
    statement2;
else
    statement-n;

If you want, you can add a body delimited by curly brackets to any of the conditions:

if(condition1){
    statement1;
}
else if(condition2) {
    statement2;
}
else {
    statement-n;
}

Practical LearningPractical Learning: Introducing if...else if...else

  1. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PayrollEvaluation041
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            (double, double) EstimateTaxes(double amount)
            {
                double taxes, net;
                double lessThan500, between500And3000, over3000;
    
                if (amount <= 500.00)
                {
                    lessThan500 = amount * 2.00 / 100;
                    between500And3000 = 0.00;
                    over3000 = 0.00; ;
                }
                else if ((amount > 500.00) && (amount <= 3000))
                {
                    lessThan500 = 500 * 2.00 / 100;
                    between500And3000 = (amount - 500) * 4.00 / 100;
                    over3000 = 0.00; ;
                }
                else // if (amount > 3000))
                {
                    lessThan500 = 500 * 2.00 / 100;
                    between500And3000 = 3000 * 4.00 / 100;
                    over3000 = (amount - 3000) * 5.00 / 100;
                }
    
                taxes = lessThan500 + between500And3000 + over3000;
                net = amount - taxes;
    
                return (taxes, net);
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double grossSalary = double.Parse(txtTaxableGrossIncome.Text);
    
                (double incomeTaxes, double netPay) cal = EstimateTaxes(grossSalary);
    
                txtIncomeTax.Text = cal.incomeTaxes.ToString("F");
                txtNetPay.Text = cal.netPay.ToString("F");
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:

    Accessing a Delegate

  3. In the top text box, type a number, such as 2462.68
  4. Click the Calculate button:

    Creating a Partial Class

if...else if ... else if and else

The if...else conditional statement allows you to process many conditions. The formula to follow is:

if(condition1) statement1;
else if(condition2) statement2;
. . .
else if(condition_n) statement_n;

If you are writing the code in a webpage, each statement must be included in curly brackets. The formula to follow is:

if(condition1) { statement1; }
else if(condition2) { statement2; }
. . .
else if(condition_n) { statement_n; }

The conditions would be checked from the beginning one after another. If a condition is true, then its corresponding statement would execute.

If there is a possibility that none of the conditions would respond true, you can add a last else condition and its statetement. The formula to follow is:

if(condition1)
    statement1;
else if(condition2)
    statement2;
. . .
else if(condition_n)
    statement_n;
else
    statement-n;

In a webpage, the formula to follow is:

if(condition1) {
    statement1;
}
else if(condition2) {
    statement2;
}
. . .
else if(condition_n) {
    statement_n;
}
else {
    statement-n;
}

A condition may need many statements to execute. In this case, you must delimit the statements by curly brackets:

if(condition1)
{
    if-statement_1;
    if-statement_2;
    . . .
    if-statement_n;
}
else if(condition2)
{
    else-if-1-statement_1;
    else-if-1-statement_2;
    . . .
    else-if-1-statement_n;
}
. . .
else if(condition_n)
{
    else-if-n-statement_1;
    else-if-n-statement_2;
    . . .
    else-if-n-statement_n;
}
else
{
    else-statement_1;
    else-statement_2;
    . . .
    else-statement_n;
}

Practical LearningPractical Learning: Introducing if...else if Conditions

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click Windows Forms Application (.NET Framework)
  3. Click Next
  4. Change the project Name to CompoundInterest2
  5. Click Create
  6. In the Solution Explorer, right-click Form1.cs -> Rename
  7. Type CompoundInterest and press Enter
  8. Read the message box and click Yes
  9. Still in the Solution, right-click ComppoundInterest.cs and click View Designer
  10. Design the form as follows:

    Introducing if...else if Conditions

    Control (Name) Text Other Properties
    Label   Principal:  
    TextBox txtPrincipal 0.00 TextAlign: Right
    Label   Interest Rate:  
    TextBox txtInterest Rate 0.00 TextAlign: Right
    Label   %  
    Label   Periods:  
    TextBox txtPeriods 0 TextAlign: Right
    Label   Years:  
    GroupBox   Compound Frequency  
    RadioButton rdoDaily Daily CheckAlign: MiddleRight
    RadioButton rdoQuaterly Quaterly CheckAlign: MiddleRight
    RadioButton rdoWeekly Weekly CheckAlign: MiddleRight
    RadioButton rdoSemiannually Semiannually CheckAlign: MiddleRight
    RadioButton rdoMonthly Monthly CheckAlign: MiddleRight
    RadioButton rdoAnnually Annually CheckAlign: MiddleRight
    Button btnCalculate Calculate  
    Label   Interest Earned:  
    TextBox txtInterestEarned   TextAlign: Right
    Label   Future Value:  
    TextBox txtFutureValue   TextAlign: Right
  11. Double-click the Calculate button
  12. Right-click the Code Editor and click Remove and Sort Usings
  13. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace CompoundInterest2
    {
        public partial class CompoundInterest : Form
        {
            public CompoundInterest()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double frequency;
    
                double principal = Convert.ToDouble(txtPrincipal.Text);
                double interestRate = Convert.ToDouble(txtInterestRate.Text);
                double periods = Convert.ToDouble(txtPeriods.Text);
    
                if(rdoDaily.Checked)
                    frequency = 365.00;
                else if (rdoWeekly.Checked)
                    frequency = 52.00;
                else if (rdoMonthly.Checked)
                    frequency = 12.00;
                else if (rdoQuaterly.Checked)
                    frequency = 4.00;
                else if (rdoSemiannually.Checked)
                    frequency = 2.00;
                else // if (rdoAnnually.Checked)
                    frequency = 1.00;
                
                double rate = interestRate / 100.00;
                double futureValue = principal * Math.Pow((1.00 + (rate / frequency)), frequency * periods);
    
                txtFutureValue.Text = futureValue.ToString("F");
                txtInterestEarned.Text = (futureValue - principal).ToString("F");
            }
        }
    }
  14. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Finding Out Whether a Value is Greater Than Another Value

  15. In the Principal text box, type a number such as 3450
  16. In the Interest Rate text box, type a number such as 12.50

  17. In the Periods text box, type a natural number such as 4
  18. In the Compound Frequency group box, click one of the radio buttons such as Monthly:

    Finding Out Whether a Value is Greater Than Another Value

  19. Click the Calculate button:

    Finding Out Whether a Value is Greater Than Another Value

  20. Close the browser and return to your programming environment

Options on Conditional Statements

Going To a Statement

In the flow of your code, you can jump from one statement or line to another. To make this possible, the C# language forvides an operator named goto. Before using it, first create or insert a name on a particular section of code or in a method. The name, also called a label, is made of one word and it can be anything. That name is followed by a colon ":". Here is an example:

public class Exercise
{
    public static void Main()
    {
        proposition:
    }
}

In the same way, you can create as many labels as you want. The name of each label must be unique among the other labels in the same section of code (in the same scope). Here are examples:

public class Exercise
{
    public static void Main()
    {
        proposition:

something:

TimeToLeave:
    }
}

After creating the label(s), you can create a condition so that, when that condition is true, code execution would jump to a designated label. To do this, in the body of the condition, type goto followed by the label. Here are examples:

public class Exercise
{
    public static void Main()
    {
        int nbr = 248;
        double result = 0;

        if( nbr < 200)
            goto proposition;
        else
            goto something;

		proposition:
	    	result = 245.55;

		something:
	    	result = 105.75;
    }
}

Negating a Statement

As you should be aware by now, Boolean algebra stands by two values, True and False, that are opposite each other. If you have a Boolean value or expression, to let you validate its opposite, the C-based languages provide the ! operator that is used to get the logical reverse of a Boolean value or of a Boolean expression. The formula to use it is:

!expression

To use this operator, type ! followed by a logical expression. The expression can be a simple Boolean value. To make the code easier to read, it is a good idea to put the negative expression in parentheses. Here is an example:

using System.Windows.Forms;

public class Exercise
{
    public void Create()
    {
        bool employeeIsFullTime = true;

       string opposite = (!employeeIsFullTime).ToString();
    }
}

In this case, the ! (Not) operator is used to change the logical value of the variable. When a Boolean variable has been "notted", its logical value has changed. If the logical value was true, it would be changed to false and vice versa. Therefore, you can inverse the logical value of a Boolean variable by "notting" or not "notting" it.

Conditional Returns of Methods

Introduction

When performing its assignment, a method can encounter different situations, a method can return only one value but you can make it produce a result that depends on some condition.

Conditionally Returning a Value from a Method

We are already familiar with the ability for a function to return a value. In some cases, the value you want to return is not a simple constant: It may depend on some condition. To make this happen, you have various options.

Practical LearningPractical Learning: Conditionally Returning a Value

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the list of projects templates, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Change the project Name to DepartmentStore2
  5. Click Create
  6. In the Solution Explorer, right-click DepartmentStore2 -> Add -> Class...
  7. Type StoreItem
  8. Press Enter
  9. You can declare a variable. Then create a conditional statement. Then, every time the outcome of a condition changes, you can update the variable. Then, at the end of the function, return that variable.
    Change the code as follows:
    unamespace DepartmentStore2
    {
        public class StoreItem
        {
            public int ItemNumber { get; set; }
            public string ItemName { get; set; }
            public string Size { get; set; }
            public double UnitPrice { get; set; }
    
            public double GetDiscountRate(int days)
            {
                double discountRate = 0.00;
    
                if (days > 70)
                    discountRate = 70;
                else if (days > 50)
                    discountRate = 50;
                else if (days > 30)
                    discountRate = 35;
                else if (days > 15)
                    discountRate = 15;
    
                return discountRate;
            }
    
            public double GetDiscountAmount(double rate)
            {
                double discountAmount = 0.00;
    
                if (rate == 0.00)
                    discountAmount = 0.00;
                else
                    discountAmount = UnitPrice * rate / 100.00;
    
                return discountAmount;
            }
        }
    }
  10. In the Solution Explorer, right-click Form1.cs -> Rename
  11. Type DepartmentStore and press Enter
  12. Read the message box and click Yes
  13. In the Solution Explorer, double-click DepartmentStore.cs
  14. Design the form as follows:

    The Power of a Number

    Control (Name) Text Other Properties
    GroupBox   Item Preview:  
    Label   Item Number:  
    TextBox txtItemNumber
    Label   Item Name:  
    TextBox txtItemName  
    Label   Unit Price:
    TextBox txtUnitPrice 0.00 TextAlign: Right
    Label   Days in Store:  
    TextBox txtDaysInStore 0 TextAlign: Right
    Label   Days:  
    Button btnCalculate Evaluate Sale Record  
    GroupBox   Sale Preview  
    Label   Item Number:  
    TextBox txtRecordItemNumber TextAlign: Right
    Label   Discount Rate:  
    TextBox txtDiscountRate   TextAlign: Right
    Label   %  
    Label   Item Name:  
    TextBox txtRecordItemName  
    Label   Discount Amount:  
    TextBox txtDiscountAmount   TextAlign: Right
    Label   Marked Price:  
    TextBox txtMarkedPrice   TextAlign: Right
  15. Double-click the Calculate button
  16. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace DepartmentStore2
    {
        public partial class DepartmentStore : Form
        {
            public DepartmentStore()
            {
                InitializeComponent();
            }
    
            private void btnEvaluate_Click(object sender, EventArgs e)
            {
                StoreItem si = new StoreItem();
                
                si.ItemNumber = int.Parse(txtItemNumber.Text);
                si.ItemName = txtItemName.Text;
                si.UnitPrice = double.Parse(txtUnitPrice.Text);
                int daysInStore = int.Parse(txtDaysInStore.Text);
                
                double discountRate = si.GetDiscountRate(daysInStore);
                double discountedAmount = si.GetDiscountAmount(discountRate);
                double markedPrice = si.UnitPrice - discountedAmount;
                
                txtDiscountRate.Text = discountRate.ToString("F");
                txtDiscountAmount.Text= discountedAmount.ToString("F");
                txtMarkedPrice.Text = markedPrice.ToString("F");
    
                txtRecordItemNumber.Text = si.ItemNumber.ToString();
                txtRecordItemName.Text = si.ItemName;
            }
        }
    }
  17. To execute the project, press Ctrl + F5:

    Conditionally Returning a Value

  18. In the text boxes above the Evaluate button, enter some values as follows:
    Item Number:   258408
    Item Name:     Pinstripe Pencil Skirt
    Unit Price:    94.95
    Days in Store: 36

    Conditionally Returning a Value

  19. Click the Evaluate Sale Record button:

    Conditionally Returning a Value

  20. Close the form and return to your programming environment
  21. In our examples, we first declared a variable that was going to hold the value to return. This is not always necessary. If you already have the value or the expression to return, you can precede it with the return keyword. You can repeat this for each section where the value or expression can/must be returned.
    For examples, access the StoreItem.cs file and change the code in the class as follows:
    namespace DepartmentStore2
    {
        public class StoreItem
        {
            public int ItemNumber { get; set; }
            public string ItemName { get; set; }
            public string Size { get; set; }
            public double UnitPrice { get; set; }
    
            public double GetDiscountRate(int days)
            {
                if (days > 70)
                    return 70;
                else if (days > 50)
                    return 50;
                else if (days > 30)
                    return 35;
                else if (days > 15)
                    return 15;
                else
                    return 0;
            }
    
            public double GetDiscountAmount(double rate)
            {
                if (rate == 0)
                    return 0;
                else
                    return UnitPrice * rate / 100;
            }
        }
    }
  22. To execute the application, press Ctrl + F5
  23. Close the browser and return to your programming environment
  24. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  25. In the list of projects templates, click Windows Forms App (.NET Framework)
  26. Click Next
  27. Change the project Name to AppliancesStore2
  28. Click Create
  29. In the Solution Explorer, right-click AppliancesStore1 -> Add -> Class...
  30. In the middle list, make sure Class is selected.
    Change the file Name to MicrowaveOven
  31. Click Add
  32. Right-click inside the Code Editor -> Remove and Sort Usings
  33. Create the class as follows:
    namespace AppliancesStore2
    {
        class MicrowaveOven
        {
            public string Make        { get; set; }
            public string Model       { get; set; }
            public double Capacity    { get; set; }
            public int    MenuOptions { get; set; }
            public double Price       { get; set; }
        }
    }
    
  34. In the Solution Explorer, right-click Form1.cs and click View Designer
  35. Change the design of the form as follows:

    Introducing the Nullity

    Control (Name) Text
    GroupBox gbxDeviceSetup Device Setup
    Label   Make:
    TextBox txtManufacturrer
    Label   Model:
    TextBox txtIdentification
    Label   Capacity:
    TextBox txtVolume
    Label   Cubic-Foot
    Label   Menu Options:
    TextBox txtNumberOfMenus
    Label   Price:
    TextBox txtValue
    Button btnCreate Create
    GroupBox gbxDeviceSummary Device Summary
    Label   Make:
    TextBox txtMake
    Label   Model:
    TextBox txtModel
    Label   Capacity:
    TextBox txtCapacity
    Label   Cubic-Foot
    Label   Menu Options:
    TextBox txtMenuOptions
    Label   Price:
    TextBox txtPrice
  36. Double-click the Create button
  37. Right-click somewhere in the Code Editor and click Remove and Sort Usings

Returning From a Method

Normally, when defining a void method, it doesn't return a value. Here is an example:

public class Exercise
{
    private void Show()
    {
    }
}

In reality, a void method can perform a return, as long as it does not return a true value. This is used to signal to the compiler that it is time to get out of the method. To add such as flag, in the appropriate section of the void method, simply type return;. Here is an example:

public class Exercise
{
    private void Show()
    {
        Blah Blah Blah
        
        return;
    }
}

In this case, the return; statement doesn't serve any true purpose. It can be made useful when associated with a conditional statement.

Exiting Early From a Method

One of the goals of a condition statement is to check a condition in order to reach a conclusion. One of the goals of a function is to perform an action if a certain condition is met. In fact, by including a condition in a function, you can decide whether the action of a function is worth pursuing or completing. In the body of a function where you are checking a condition, once you find out that a certain condition is not met, you can stop checking the condition and get out of the function. This is done with the return keyword. To apply it, in the body of a conditional statement in a function, once you decide that the condition reaches the wrong outcome, type return and a semicolon.

Practical LearningPractical Learning: Exiting Early From a Method

  1. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace AppliancesStore2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void Present(MicrowaveOven mo)
            {
                if (mo is null)
                {
                    MessageBox.Show("Ain't no microwave oven like that in the store.",
                                    "Appliances Store");
                    return;
                }
    
                txtMake.Text = mo.Make;
                txtModel.Text = mo.Model;
                txtCapacity.Text = mo.Capacity.ToString();
                txtMenuOptions.Text = mo.MenuOptions.ToString();
                txtPrice.Text = mo.Price.ToString("F");
            }
            
            void CreateStoreItem(out MicrowaveOven device)
            {
                device = new MicrowaveOven();
    
                if (txtManufacturer.Text == "")
                {
                    MessageBox.Show("You must provide the name of the company that manufactures the microwave oven.",
                                    "Appliances Store");
                    return;
                }
    
                if (txtVolume.Text == "")
                {
                    MessageBox.Show("What it the capacity of the microwave oven?",
                                    "Appliances Store");
                    return;
                }
    
                if (txtNumberOfMenus.Text == "")
                {
                    MessageBox.Show("How many menu options does the microwave oven have?",
                                    "Appliances Store");
                    return;
                }
    
                if (txtValue.Text == "")
                {
                    MessageBox.Show("You must indicate the price of the microwave oven.",
                                    "Appliances Store");
                    return;
                }
    
                device = new MicrowaveOven()
                {
                    Make = txtManufacturer.Text,
                    Model = txtIdentification.Text,
                    Capacity = double.Parse(txtVolume.Text),
                    MenuOptions = int.Parse(txtNumberOfMenus.Text),
                    Price = double.Parse(txtValue.Text)
                };
            }
    
            private void btnCreate_Click(object sender, EventArgs e)
            {
                MicrowaveOven mo = new MicrowaveOven();
    
                CreateStoreItem(out mo);
                Present(mo);
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:

    Introducing the Nullity

  3. Click the Create button:

    Introducing the Nullity

  4. Click OK on the message box
  5. In the Make text box, type Samsung and click the Create button
  6. Click the Create button:

    Introducing the Nullity

  7. Click OK on the message box
  8. Complet the form with the other piece of information as follows:
    Nake: Samsung
    Model: ME16K3000AS
    Capacity: 1.6
    Menu Options: 10
    Price: 198.85

    Introducing the Nullity

  9. Click the Create button:

    Introducing the Nullity

  10. Close the form and return to Microsoft Visual Studio

Introduction to Recursion

Recursion if the ability for a method (or functtion) to call itself. A possible problem is that the method could keep calling itself and never stops. Therefore, the method must define how it would stop calling itself and get out of the body of the method.

A type of formula to create a recursive method is:

return-value method-name(parameter(s), if any)
{
    Optional Action . . .
    method-name();
    Optionan Action . . .
}

A recursive method starts with a return value. If it would not return a value, you can define it with void. After its name, the method can use 0, one, or more parameters. Most of the time, a recursive method uses at least one parameter that it would modify. In the body of the method, you can take the necessary actions. There are no particular steps to follow when implementing a recursive method but there are two main rules to observe:

For an example of counting decrementing odd numbers, you could start by creating a method that uses a parameter of type integer. To exercise some control on the lowest possible values, we will consider only positive numbers. In the body of the method, we will display the current value of the argument, subtract 2, and recall the method itself. Here is our method:

namespace Exercises
{
    public class Exercise
    {
        public int Number = 0;

        public void OddNumbers(int a)
        {
            if (a >= 1)
            {
                Number += a;

                a -= 2;
                OddNumbers(a);
            }
        }
    }
}
-------------------------------------------
Exercise exo = new Exercise();

const int number = 9;
hc.OddNumbers(number);

Notice that the method calls itself in its body.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2021, FunctionX Next