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:
using System;
public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");
return;
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
return 0;
}
}
In this case, the return; operation doesn't serve any
true purpose. In the next section, we will see how it can be made useful
when associated with a conditional statement.
Application:
Introducing Methods and Conditions
|
|
- Start Microsoft Visual Studio
- To create a new application, on the main menu, click File -> New
Project...
- In the middle list, click Empty Project
- Change the Name to NationalBank5 and press Enter
- To create a new file, on the main menu, click Project -> Add New
Item...
- In the middle list, click Code File
- Change the Name of the file to Customer
- Click Add
- Complete the Customer.cs file as follows:
public enum AccountType { Checking, Saving, Other }
public class Customer
{
public string AccountNumber;
public AccountType Type;
public string FullName;
public double Balance;
public short PIN;
public Customer(string acnt = "000-000000-000",
AccountType category = AccountType.Other,
string name = "John Doe")
{
AccountNumber = acnt;
Type = category;
FullName = name;
PIN = 0;
Balance = 0.00D;
}
}
- To create a new file, in the Solution Explorer, right-click
NationalBank5 -> Add -> New Item...
- In the middle list, make sure Code File is selected.
Change the
Name to Management and press Enter
- Complete the file as follows:
using System;
public class Management
{
private Customer CreateNewAccount()
{
byte typeOfAccount = 0;
Customer client = new Customer();
Console.WriteLine("===========================================");
Console.WriteLine("==-= National Bank =-======================");
Console.WriteLine("-------------------------------------------");
Console.Write("Enter a number for the new account(000-000000-000): ");
client.AccountNumber = Console.ReadLine();
Console.WriteLine("What type of account the customer wants to open");
Console.WriteLine("1 - Checking Account");
Console.WriteLine("2 - Savings Account");
Console.Write("Enter account type: ");
typeOfAccount = byte.Parse(Console.ReadLine());
if (typeOfAccount == 1)
client.Type = AccountType.Checking;
else if (typeOfAccount == 2)
client.Type = AccountType.Saving;
else
client.Type = AccountType.Other;
Console.Write("Enter customer name: ");
client.FullName = Console.ReadLine();
Console.Write("Ask the customer to enter a PIN: ");
client.PIN = short.Parse(Console.ReadLine());
return client;
}
public double GetMoney()
{
double amount = 0;
Console.Write("Amount: ");
amount = double.Parse(Console.ReadLine());
return amount;
}
private void ShowAccountInformation(Customer cust)
{
Console.WriteLine("===========================================");
Console.WriteLine("==-= National Bank =-======================");
Console.WriteLine("Customer Account Information");
Console.WriteLine("-------------------------------------------");
Console.WriteLine("Account #: {0}", cust.AccountNumber);
Console.WriteLine("Account Type: {0}", cust.Type);
Console.WriteLine("Full Name: {0}", cust.FullName);
Console.WriteLine("PIN #: {0}", cust.PIN);
Console.WriteLine("Balance: {0:F}", cust.Balance);
Console.WriteLine("===========================================");
return;
}
public static int Main()
{
double amount = 0;
byte nextAction = 0;
Customer accountHolder = null;
Management registration = new Management();
Console.Title = "National Bank";
accountHolder = registration.CreateNewAccount();
Console.WriteLine("Enter the customer's initial deposit");
accountHolder.Balance = registration.GetMoney();
Console.Clear();
registration.ShowAccountInformation(accountHolder);
do
{
Console.WriteLine("What do you want to do now?");
Console.WriteLine("1 - Check account balance");
Console.WriteLine("2 - Make a deposit");
Console.WriteLine("3 - Withdraw money");
Console.WriteLine("4 - Transfer money from one account to another");
Console.Write("Enter your choice: ");
nextAction = byte.Parse(Console.ReadLine());
Console.Clear();
switch (nextAction)
{
case 1:
Console.Clear();
registration.ShowAccountInformation(accountHolder);
Console.Write("Press Enter for next operation");
Console.ReadKey();
break;
case 2:
Console.Write("Enter Deposit ");
amount = registration.GetMoney();
accountHolder.Balance = accountHolder.Balance + amount;
Console.Clear();
registration.ShowAccountInformation(accountHolder);
break;
case 3:
Console.Write("Enter Withdrawal ");
amount = registration.GetMoney();
if (amount > accountHolder.Balance)
{
Console.WriteLine(
"You are not allowed to withdraw more money than your account has.");
Console.ReadKey();
}
else
accountHolder.Balance = accountHolder.Balance - amount;
Console.Clear();
registration.ShowAccountInformation(accountHolder);
break;
case 4:
Console.WriteLine(
"Operation not available: You have only one account with us");
break;
}
if ((nextAction < 1) || (nextAction > 4))
Console.WriteLine(
"Invalid Action: Please enter a value between 1 and 4");
} while ((nextAction >= 1) && (nextAction <= 4));
Console.ReadKey();
return 0;
}
}
Some functions are meant to return a value that is
conditional of their processing. The fact that a function indicates the type
of value it would return may not be clear at the time the function is closed
but a function defined other than void must always return a value.
You can write a conditional statement, such as if, inside of a function and
return a value from that condition. Here is an example:
using System;
public class Program
{
enum HouseType { Unknown, SingleFamily, Townhouse, Condominium };
public static int Main()
{
var type = GetHouseType();
switch (type)
{
case HouseType.SingleFamily:
Console.WriteLine("\nType of Home: Single Family");
break;
case HouseType.Townhouse:
Console.WriteLine("\nType of Home: Townhouse");
break;
case HouseType.Condominium:
Console.WriteLine("\nType of Home: Condominium");
break;
case HouseType.Unknown:
Console.WriteLine("\nType of Home. Unknown");
break;
}
return 0;
}
private static HouseType GetHouseType()
{
var type = 0;
Console.WriteLine("What Type of House Would you Like to Purchase?");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Townhouse");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice? ");
type = int.Parse(Console.ReadLine());
if (type == 1)
return HouseType.SingleFamily;
else if (type == 2)
return HouseType.Townhouse;
else if (type == 3)
return HouseType.Condominium;
}
}
This GetHouseType() method indicates when one of three
values is returned. In reality, this method could get a value other than the
three that are considered. If the user enters such a value, the current
version of the method would not know what to do. For this reason, the
program will not compile. In Microsoft Visual C#, you would receive the
following error:
'Program.GetHouseType()': not all code paths return a value
To solve this problem, you must provide a statement that
would include any value other than those considered. You can do this by
writing a final return that has its own value. Here is an example:
using System;
public class Program
{
enum HouseType { Unknown, SingleFamily, Townhouse, Condominium };
public static int Main()
{
var type = GetHouseType();
switch (type)
{
case HouseType.SingleFamily:
Console.WriteLine("\nType of Home: Single Family");
break;
case HouseType.Townhouse:
Console.WriteLine("\nType of Home: Townhouse");
break;
case HouseType.Condominium:
Console.WriteLine("\nType of Home: Condominium");
break;
case HouseType.Unknown:
Console.WriteLine("\nType of Home. Unknown");
break;
}
return 0;
}
private static HouseType GetHouseType()
{
var type = 0;
Console.WriteLine("What Type of House Would you Like to Purchase?");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Townhouse");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice? ");
type = int.Parse(Console.ReadLine());
if (type == 1)
return HouseType.SingleFamily;
else if (type == 2)
return HouseType.Townhouse;
else if (type == 3)
return HouseType.Condominium;
else
return HouseType.Unknown;
}
}
Application:
Conditionally Returning a Value
|
|
- Change the Management.cs file as follows:
using System;
public class Management
{
private AccountType SpecifyAccountType()
{
byte type = 0;
Console.WriteLine("What type of account the customer wants to open");
Console.WriteLine("1 - Checking Account");
Console.WriteLine("2 - Savings Account");
Console.Write("Enter account type: ");
type = byte.Parse(Console.ReadLine());
if (type == 1)
return AccountType.Checking;
else if (type == 2)
return AccountType.Saving;
else
return AccountType.Other;
}
private Customer CreateNewAccount()
{
Customer client = new Customer();
. . . No Change
return client;
}
public double Deposit()
{
double amount = 0;
Console.Write("Amount to deposit: ");
amount = double.Parse(Console.ReadLine());
return amount;
}
public double Withdraw(Customer cust)
{
double amount = 0;
Console.Write("Amount to withdraw: ");
amount = double.Parse(Console.ReadLine());
if (amount > cust.Balance)
{
Console.WriteLine(
"You are not allowed to withdraw more money than your account has.");
Console.ReadKey();
return 0.00D;
}
else
return amount;
}
private void ShowAccountInformation(Customer cust)
{
. . . No Change
}
public static int Main()
{
double amount = 0;
byte nextAction = 0;
Customer accountHolder = null;
Management registration = new Management();
Console.Title = "National Bank";
accountHolder = registration.CreateNewAccount();
Console.WriteLine("Enter the customer's initial deposit");
accountHolder.Balance = registration.Deposit();
Console.Clear();
registration.ShowAccountInformation(accountHolder);
do
{
Console.WriteLine("What do you want to do now?");
Console.WriteLine("0 - Close the application");
Console.WriteLine("1 - Check account balance");
Console.WriteLine("2 - Make a deposit");
Console.WriteLine("3 - Withdraw money");
Console.WriteLine("4 - Transfer money from one account to another");
Console.Write("Enter your choice: ");
nextAction = byte.Parse(Console.ReadLine());
Console.Clear();
switch (nextAction)
{
case 1:
Console.Clear();
registration.ShowAccountInformation(accountHolder);
Console.Write("Press Enter for next operation");
Console.ReadKey();
break;
case 2:
amount = registration.Deposit();
accountHolder.Balance += amount;
Console.Clear();
registration.ShowAccountInformation(accountHolder);
break;
case 3:
amount = registration.Withdraw(accountHolder);
accountHolder.Balance -= amount;
Console.Clear();
registration.ShowAccountInformation(accountHolder);
break;
case 4:
Console.WriteLine(
"Operation not available: You have only one account with us");
break;
default:
return 0;
}
if ((nextAction < 1) || (nextAction > 4))
Console.WriteLine(
"Invalid Action: Please enter a value between 1 and 4");
} while ((nextAction >= 1) && (nextAction <= 4));
Console.ReadKey();
return 0;
}
}
- Press F5 to execute
- Enter information as follows:
Account #: |
257-484902-444 |
Account Type: |
1 |
Customer Name: |
Josh Nay |
PIN: |
5008 |
Initial Deposit |
250 |
===========================================
==-= National Bank =-======================
-------------------------------------------
New Account Number (000-000000-000): 257-484902-444
What type of account the customer wants to open
1 - Checking Account
2 - Savings Account
Enter account type: 1
Enter customer name: Josh Nay
Ask the customer to enter a PIN: 5008
Enter the customer's initial deposit
Amount to deposit: 250
- Press Enter
===========================================
==-= National Bank =-======================
Customer Account Information
-------------------------------------------
Account #: 257-484902-444
Account Type: Checking
Full Name: Josh Nay
PIN #: 5008
Balance: 250.00
===========================================
What do you want to do now?
0 - Close the application
1 - Check account balance
2 - Make a deposit
3 - Withdraw money
4 - Transfer money from one account to another
Enter your choice:
- When asked to specify the next action, type 3 to
withdraw money and press Enter
- Type 164.37 as the amount to deposit and press
Enter
===========================================
==-= National Bank =-======================
Customer Account Information
-------------------------------------------
Account #: 257-484902-444
Account Type: Checking
Full Name: Josh Nay
PIN #: 5008
Balance: 85.63
===========================================
What do you want to do now?
0 - Close the application
1 - Check account balance
2 - Make a deposit
3 - Withdraw money
4 - Transfer money from one account to another
Enter your choice:
- For the next action, type 2 and press Enter
- Type 116.18 as the amount to deposit and press
Enter
===========================================
==-= National Bank =-======================
Customer Account Information
-------------------------------------------
Account #: 257-484902-444
Account Type: Checking
Full Name: Josh Nay
PIN #: 5008
Balance: 201.81
===========================================
What do you want to do now?
0 - Close the application
1 - Check account balance
2 - Make a deposit
3 - Withdraw money
4 - Transfer money from one account to another
Enter your choice:
- For the next action, type 3 and press Enter
- Type 300 as the amount to withdraw and press Enter
Amount to withdraw: 300
You are not allowed to withdraw more money than your account has.
- Press Enter
- Type 0 as the next action and press Enter
For the different situations in which we used a while
condition so far, we included a means of checking the condition. Instead,
you can include juste the true Boolean constant in the parentheses of true.
Here is an example:
using System;
public class Exercise
{
public static int Main()
{
while (true)
Console.WriteLine("C# Programming is fun!!!");
return 0;
}
}
This type of statement is legal and would work fine. But
it has no way of stopping because it is telling the compiler "As long as
this is true, ...". The question is, what is "this"? As a result, the
program would run for ever. Therefore, if you create a while(true)
condition, in the body of the statement, you should provide a way for the
compiler to stop, that is, a way for The condition to be false. This can be
done by include an if condition. Here is an example:
using System;
public class Exercise
{
public static int Main()
{
int i = 0;
while (true)
{
if (i > 8)
break;
Console.WriteLine("C# Programming is fun!!!");
i++;
}
return 0;
}
}
This time, the program is asking the compiler to keep
displaying a sentence in the console screen by counting from 0 and up; but
if the count reaches 8, to stop. The above program would produce:
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
Press any key to continue . . .
In the above program, we used a break operator. You can
use any other mechanism that can stop the looping, as long as at one time
the condition would be false. Therefore, here is another way of stopping a
while(true) loop:
using System;
public class Exercise
{
public static int Main()
{
int i = 0;
while (true)
{
if (i < 8)
Console.WriteLine("C# Programming is fun!!!");
else
return 0;
i++;
}
}
}
This would produce the same result as previously.
Instead of using while(true), you can first declare and
initialize a Boolean variable, or you can use a Boolean variable whose value
is already known. The value can come from a method or by other means.
Application:
Using while(true)
|
|
- To start a new application, on the main menu, click File -> New
Project...
- In the middle list, click Empty Project
- Change the name to DepartmentStore8
- To create a new class, on the main menu, click Project -> Add
Class...
- Change the Name to StoreItem and click Add
- Change the document as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DepartmentStore8
{
public class StoreItem
{
public int itemNumber;
public string itemName;
public string itemSize;
public decimal unitPrice;
public StoreItem()
{
itemNumber = 0;
itemName = "";
itemSize = "";
unitPrice = 0.00M;
}
public StoreItem(int code, string name,
string size, decimal price)
{
itemNumber = code;
itemName = name;
itemSize = size;
unitPrice = price;
}
}
}
- In the Solution Explorer, right-click DepartmentStore8 -> Add -> New
Item...
- In the middle list, click Code File
- Change the Name to Inventory and press Enter
- Change the file as follows:
using System;
using DepartmentStore8;
public class Inventory
{
static int Main()
{
StoreItem si = null;
bool itemIsValid = true;
Console.Title = "Department Store Inventory";
Console.WriteLine("Department Store Inventory");
while (itemIsValid)
{
si = new StoreItem();
Console.WriteLine("------------------------");
Console.Write("Enter Item #: ");
si.itemNumber = int.Parse(Console.ReadLine());
if (si.itemNumber < 0)
itemIsValid = false;
else
{
Console.Write("Enter Item Name: ");
si.itemName = Console.ReadLine();
Console.Write("Enter Item Size: ");
si.itemSize = Console.ReadLine();
Console.Write("Enter Unit Price: ");
si.unitPrice = decimal.Parse(Console.ReadLine());
Console.WriteLine("=-= Store Item =-=");
Console.WriteLine("Item #: {0}", si.itemNumber);
Console.WriteLine("Item Name: {0}", si.itemName);
Console.WriteLine("Size: {0}", si.itemSize);
Console.WriteLine("Unit Price: {0}", si.unitPrice);
}
}
return 0;
}
}
- Execute the application to test it
- When requested, provide the data as follows:
Item Number: |
279475 |
Item Name: |
Wool Jersey Ruffle Dress |
Size: |
8 |
Unit Price: |
150 |
Item Number: |
729070 |
Item Name: |
Mid-Weight Flat-Front Wool Trouser Pants |
Size: |
36W - 30L |
Unit Price: |
69.95 |
Item Number: |
297004 |
Item Name: |
Ponte Pencil Skirt with Pleated Detail |
Size: |
16 |
Unit Price: |
80 |
Item Number: |
-1 |
Department Store Inventory
------------------------
Enter Item #: 279475
Enter Item Name: Wool Jersey Ruffle Dress
Enter Item Size: 8
Enter Unit Price: 150
=-= Store Item =-=
Item #: 279475
Item Name: Wool Jersey Ruffle Dress
Size: 8
Unit Price: 150
------------------------
Enter Item #: 729070
Enter Item Name: Mid-Weight Flat-Front Wool Trouser Pants
Enter Item Size: 36W - 30L
Enter Unit Price: 69.95
=-= Store Item =-=
Item #: 729070
Item Name: Mid-Weight Flat-Front Wool Trouser Pants
Size: 36W - 30L
Unit Price: 69.95
------------------------
Enter Item #: 297004
Enter Item Name: Ponte Pencil Skirt With Pleated Detail
Enter Item Size: 16
Enter Unit Price: 80
=-= Store Item =-=
Item #: 297004
Item Name: Ponte Pencil Skirt With Pleated Detail
Size: 16
Unit Price: 80
------------------------
Enter Item #: -1
- Close the DOS window and return to your programming environment
Imagine that you want to count the positive odd numbers
from a certain maximum to a certain minimum. For example, to count the odd
numbers from 1 to 9, you would use:
9, 7, 5, 3, and 1
Notice that, to perform this operation, you consider the
highest. Then you subtract 2 to get the previous. Again, you subtract 2 from
the number to get the previous. What you are simply doing is to subtract a
constant to what you already have and you invent very little. In computer
programming, you can solve this type of problem by first writing a function,
and then have the function call itself. This is the basis for recursion.
Application:
Introducing Recursion
|
|
- To start a new application, on the main menu, click File -> New
Project...
- In the middle list, click Empty Project
- Change the nema to Recursions and press Enter
- In the Solution Explorer, right-click Recursions -> Add -> New Item
- In the middle list, click Code File
- Change the name to Calculator and press Enter
Creating a Recursive Method
|
|
A type of formula to create a recursive method is:
ReturnValue Function(Arguments, if any)
{
Optional Action . . .
Function();
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 take one or more arguments. Most of the time, a
recursive method takes at least one argument that it would then 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:
- In its body, the method must call itself
- Before or after calling itself, the method must check a condition
that would allow it to stop, otherwise, it might run continuously
For our example of counting decrementing odd numbers,
you could start by creating a method that takes an integer as argument. 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
function:
using System;
public class Exercise
{
static void OddNumbers(int a)
{
if (a >= 1)
{
Console.Write("{0}, ", a);
a -= 2;
OddNumbers(a);
}
}
public static int Main()
{
const int number = 9;
Console.WriteLine("Odd Numbers");
OddNumbers(number);
Console.WriteLine();
return 0;
}
}
Notice that the method calls itself in its body. This
would produce:
Odd Numbers
9, 7, 5, 3, 1,
Press any key to continue . . .
Application:
Creating a Recursive Method
|
|
- To create a recursive function, change the document as follows:
using System;
public class Calculator
{
private long Factorial(long number)
{
if (number <= 1)
return 1;
return number * Factorial(number - 1);
}
public static int Main()
{
long factor = 0;
Calculator exo = new Calculator();
Console.Write("To calculate a factorial, enter a (small positive) number: ");
factor = long.Parse(Console.ReadLine());
Console.WriteLine("The factorial of {0} = {1}",
factor, exo.Factorial(factor));
System.Console.ReadKey();
return 0;
}
}
- Execute the application to test it
- When asked to provide a number, type 8 and press
Enter:
To calculate a factorial, enter a (small positive) number: 8
The factorial of 8 = 40320
Press any key to continue . . .
- Press Enter to close the DOS window
Recursive methods provide a valuable mechanism for
building lists or series, which are value that are either increment or
decrement but follow a pattern. Imagine that, instead of simply displaying
odd numbers as we did above, you want to add them incrementally. If you have
1, it would also produce 1. If you have 5, you would like to add 1 to 3,
then the result to 5, and so on. This can be illustrated as follows:
1 = 1
|
1 + 3 = 4
|
1 + 3 + 5 = 9
|
1 + 3 + 5 + 7 = 16
|
1 + 3 + 5 + 7 + 9 = 25
|
To perform this operation, you would consider 1. If the
number is less than or equal to 1, the method should return 1. Otherwise,
add 2 to 1, then add 2 to the new result. Continue this until you get to the
value of the argument. The method can be implemented as follows:
using System;
public class Exercise
{
static int AdditionalOdd(int a)
{
if (a <= 1)
return 1;
return a + AdditionalOdd(a - 2);
}
static void OddNumbers(int a)
{
if (a >= 1)
{
Console.Write("{0}, ", a);
a -= 2;
OddNumbers(a);
}
}
public static int Main()
{
const int Number = 9;
Console.WriteLine("Odd Numbers");
OddNumbers(Number);
Console.WriteLine();
Console.WriteLine("Sum of Odds: {0}\n", AdditionalOdd(Number));
return 0;
}
}
This would produce:
Odd Numbers
9, 7, 5, 3, 1,
Sum of Odds: 25
Press any key to continue . . .
Application:
Using Recursive Methods
|
|
- Change the document as follows:
using System;
public class Calculator
{
private long Factorial(long number)
{
if (number <= 1)
return 1;
return number * Factorial(number - 1);
}
private long Permutation(long n, long r)
{
if (r == 0)
return 0;
if (n == 0)
return 0;
if ((r >= 0) && (r <= n))
return Factorial(n) / Factorial(n - r);
else
return 0;
}
private long Combinatorial(long a, long b)
{
if (a <= 1)
return 1;
return Factorial(a) / ((Factorial(b) * Factorial(a - b)));
}
public static int Main()
{
long factor = 0;
long second = 0;
Calculator exo = new Calculator();
Console.Write("To calculate a factorial, enter a (small positive) number: ");
factor = long.Parse(Console.ReadLine());
Console.Write("To calculate a permutation and the combination, enter a second (small positive) number: ");
second = long.Parse(Console.ReadLine());
Console.WriteLine("Factorial: F({0}) = {1}",
factor, exo.Factorial(factor));
Console.WriteLine("Permutation: P({0}, {1}) = {2}",
factor, second, exo.Permutation(factor, second));
Console.WriteLine("Combination: C({0}, {1}) = {2}",
factor, second, exo.Combinatorial(factor, second));
System.Console.ReadKey();
return 0;
}
}
- Execute the application to test it
- When asked to provide a number, type 20 and press
Enter
- When asked to provide a second number, type 5 and
press Enter:
To calculate a factorial, enter a (small positive) number: 20
To calculate a permutation and the combination, enter a second (small positive)
number: 5
Factorial: F(20) = 2432902008176640000
Permutation: P(20, 5) = 1860480
Combination: C(20, 5) = 15504
- Press Enter to close the DOS window
- On the main menu, click File -> Close Solution
- When asked whether you want to save, click No
|
|