0% found this document useful (0 votes)
25 views40 pages

CSC221 Lecture 4

Uploaded by

iceomgbbh345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views40 pages

CSC221 Lecture 4

Uploaded by

iceomgbbh345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Week Four

Modularizing Your Code with Methods

The CSC 221 Team


[2023/2024]
LECTURE OUTLINE

 Introduction to Methods
 Void Methods
 Passing Arguments to Methods
 Passing Arguments by Reference
 Debugging Methods
Introduction to Methods
 Methods can be used to break a complex program into small,
manageable pieces.
 A void method simply executes a group of statements and then terminates.
 A value-returning method returns a value to the statement that called it.
 For example, if you have a method that calculates the maximum value
in an array, you can use this method from any point in your code, and
use the same lines of code in each case.
 This concept is referred to as reusability.
Advantages of Method

 Methods make your code more readable, as you can use them to
group related code together, thereby reducing the length of your code.
 Methods can also be used to create multipurpose code, enabling them
to perform the same operations on varying data.
 For example, you could supply an array to search as a parameter and obtain the
maximum value in the array as a return value. This means that you can use the
same method to work with a different array each time.
Methods

 A method is a collection of statements that performs a specific


task. So far, you have experienced methods in the following two
ways:
 You have created event handlers. An event handler is a special type of
method that responds to events.
 You have executed predefined methods from the .NET Framework, such as
MessageBox.Show and the TryParse methods.
5
Void Methods

 A void method performs a task and then terminates. It does not


return a value back to the statement that called it.
 A method definition has two parts: a header and a body.
 The method header, which appears at the beginning of a method definition,
lists several important things about the method, including the method’s name.
 The method body is a collection of statements that are performed when the
method is executed. These statements are enclosed inside a set of curly braces.

6
Method Definition

7
Method Header Components
 Access modifier - The keyword private is an access modifier. When a method is
declared as private, it can be called only by code inside the same class as the
method.
 Return type (void) - It does not return a value back to the statement that called it.
 Method name - The method in this example is named DisplayMessage, so we
can easily guess what the method does: It displays a message.
 Parentheses - In the header, the method name is always followed by a set of
parentheses.
Note: The method header is never terminated with a semicolon.
8
The Method Body

 Beginning at the line after the method header, one or more


statements appear inside a set of curly braces ({ }).
 These statements are the method’s body and are performed any time the
module is executed.

9
Calling a Method
 A method executes when it is called. Event handlers are called when
specific events take place, but other methods are executed by method
call statements.
 When a method is called, the program branches to that method execute
the statements in its body.
 Here is an example of a method call statement that calls the
DisplayMessage method we previously examined:
DisplayMessage(); 10
11
Class Task 1: The Simple Method application’s form
namespace Simple_Method
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void goButton_Click(object sender, EventArgs e)


{
MessageBox.Show("This is the goButton_Click method.");
DisplayMessage();
MessageBox.Show("Back in the goButton_Click method.");
}

private void DisplayMessage()


{
MessageBox.Show("This is the DisplayMessage method.");
}
}
}

Code for the Simple Method application’s Form1 form 12


Passing Arguments to Methods
 An argument is any piece of data that is passed into a method
when the method is called.
 MessageBox.Show("Hello");
Arguments
 number = int.Parse(str);
 A parameter is a variable that receives an argument that is passed
into a method.
 See next slide

13
private void DisplayValue(int value)
{
MessageBox.Show(value.ToString()); Parameter
}

// Things in between …

DisplayValue(x); // call to DisplayValue() with variable x as the argument

DisplayValue(x * 4); // another call to DisplayValue()

DisplayValue(int.Parse("700")); // another call, the argument is 700

A method with only one parameter and sample calls 14


Compatibility Rules in C#

 You can pass only string arguments into string parameters.


 You can pass int arguments into int parameters, but you cannot pass double or
decimal arguments into int parameters.
 You can pass either double or int arguments into double parameters, but you
cannot pass decimal values into double parameters.
 You can pass either decimal or int arguments to decimal parameters, but you
cannot pass double arguments into decimal parameters.

15
Example/Class Activity

 Implement a function that returns the binary value of an integer.


 Design a form that has a textbox for collecting the input (an integer) and
another label/textbox for displaying the output (binary value)
 Finally, add a button, such that when the button is clicked, the binary value
of the integer in the input textbox is displayed.

16
private void button1_Click(object sender, EventArgs e)
{
int input;
string output;
if (int.TryParse(textBox1.Text, out input))
{
output = getBinaryValue(input);
textBox2.Text = output;
}
else
{
MessageBox.Show("Input is not an integer value, try again");
}
}

Interface + Implementation of the “Convert” button 17


private string getBinaryValue(int value)
{
if (value == 0)
return "0";
string output = "";
int remainder;
while(value > 0)
{
remainder = value % 2;
value = value / 2;
output = remainder.ToString() + output;
}

return output;
}

Implementation of the getBinaryValue() function 18


Passing Multiple Arguments – Example 19
Default Arguments

 C# allows you to provide a default argument for a method


parameter.
 When a default argument is provided for a parameter, it becomes
possible to call the method without explicitly passing an argument
into the parameter.
 Here is an example of a method that has a parameter with a default argument
(see next slide)

20
private void ShowTax(decimal price, decimal taxRate = 0.07m)
{
// Calculate the tax.
decimal tax = price * taxRate;
// Display the tax.
MessageBox.Show("The tax is " + tax.ToString("c"));
}

ShowTax() method: taxRate parameter has a default argument 21


private void button1_Click(object sender, EventArgs e)
{
decimal price, taxRate;
if (decimal.TryParse(textBox1.Text, out price))
{
if(textBox2.Text != String.Empty &&
decimal.TryParse(textBox2.Text, out taxRate))
ShowTax(price, taxRate);
else
ShowTax(price);
}
else
{
MessageBox.Show("Invalid input format");
}
}

if(textBox2.Text != String.Empty && decimal.TryParse(textBox2.Text, out taxRate))

“Compute” button 22
1 2

3
Can you explain the outputs?

Notice showPrice() can be called without


passing the second argument. In this case,
the method simply uses the default value
0.07.

Different outputs, Outputs (1) and (3) used 0.07 as the tax rate! 23
Passing Arguments by Value

 When an argument is passed by value, only a copy of the


argument’s value is passed into the parameter variable.
 If the contents of the parameter variable are changed inside the
method, it has no effect on the argument in the calling part of the
program.

24
private void goButton_Click(object sender, EventArgs e)
{
int number = 99;
// Display the value of number.
MessageBox.Show("The value of number is " + number);
// Call ChangeMe, passing number as an argument.
ChangeMe(number);
// Display the value of number again.
MessageBox.Show("The value of number is " + number);
}

private void ChangeMe(int myValue)


{
// Change the value of the myValue parameter.
myValue = 0;

// Display the value of myValue.


MessageBox.Show("In ChangeMe, myValue is " + myValue);
}

Passing Arguments by Value Application Code


Sequence of messages displayed by the Pass By Value application
Passing Arguments by Reference

 When an argument is passed by reference to a method, the method


can change the value of the argument in the calling part of the
program.
 When you want a method to be able to change the value of a variable that
is passed to it as an argument, the variable must be passed by reference.
 In C#, there are two ways to pass an argument by reference:
 You can use a reference parameter in the method.
 You can use an output parameter in the method.
27
Using Reference Parameters

 In C#, you declare a reference parameter by writing the ref keyword before the parameter variable’s data type.

private void SetToZero(ref int number)


{
number = 0;
}

 When you call a method that has a reference parameter, you must also write the keyword ref before the argument.
The following code sample shows an example:

int myVar = 99;


SetToZero(ref myVar);
28
private void setToZero(ref int x)
{
x = 0;
}

private void button1_Click(object sender, EventArgs e)


{
int val = int.Parse(textBox1.Text);
MessageBox.Show("Value before the method call: Var = " + val);
setToZero(ref val);
MessageBox.Show("Value after the method call: Var = " + val);
}

Example 29
Boolean Methods

 A Boolean method returns either true or false. You can use a Boolean
method to test a condition, and then return either true or false to indicate
whether the condition exists.

 Boolean methods are useful for simplifying complex conditions that are
tested in decision and repetition structures.

30
private bool IsEven(int number)
{
// Local variable to hold true or false
bool numberIsEven;
// Determine whether the number is even.
if (number % 2 == 0)
{
numberIsEven = true;
}
else
{
numberIsEven = false;
}
// Return the result.
return numberIsEven;
}

A Boolean method named IsEven


31
In this tutorial, you complete an application that lets you enter an employee’s gross pay
and bonus amount and calculates the amount of retirement contribution.

The Pay and Bonus application’s form using Boolean Method 32


private bool InputIsValid(ref decimal pay, ref decimal bonus)
{
// Flag variable to indicate whether the input is good
bool inputGood = false;
// Try to convert both inputs to decimal.
if (decimal.TryParse(grossPayTextBox.Text, out pay))
{
if (decimal.TryParse(bonusTextBox.Text, out bonus))
{
// Both inputs are good.
inputGood = true;
}
else
{
// Display an error message for the bonus.
MessageBox.Show("Bonus amount is invalid.");
}
} // The else part is on the next slide.
InputIsValid() method – Continues on the next slide 33
else
{
// Display an error message for gross pay.
MessageBox.Show("Gross pay is invalid.");
}

// Return the result.


return inputGood;
} // end of InputIsValid method().

private void exitButton_Click(object sender, EventArgs e)


{
// Close the form.
this.Close();
}

Conclusion of InputIsValid method() and the Exit button


34
private void calculateButton_Click(object sender, EventArgs e)
{
// Variables for gross pay, bonus, and contributions
decimal grossPay = 0m, bonus = 0m, contributions = 0m;
decimal CONTRIB_RATE = 0.05m
if (InputIsValid(ref grossPay, ref bonus))
{
// Calculate the amount of contribution.
contributions = (grossPay + bonus) * CONTRIB_RATE;
// Display the contribution.
contributionLabel.Text = contributions.ToString("c");
}
}

“Calculate Contribution” Button 35


Debugging Methods
 Visual Studio debugging commands allow you to single-step
through applications with methods.
 The Step Into command allows you to single-step through a called
method.
 The Step Over command allows you to execute a method call
without single-stepping through its lines.
 The Step Out command allows you to execute all remaining lines of
a method that you are debugging without stepping through them.
36
Question 1
 Salesmen’s Commission Calculator
Create an application that lets the user enter a salesman’s revenue sale and the rate of commission paid by the
company, and displays the commission earned. For example:

• If a salesman sells $100,000 in revenue while working with a company that pays
5 percent of the revenue, his commission check will be $5,000.
• If a salesman sells $100,000 in revenue while working with a company that pays
8 percent of the revenue, his commission check will be $8,000.

The program should have a method named CalculateCommission that receives the
revenue sale by a salesman and the commission percentage as arguments, and returns
the commission earned by the salesman.

37
Question 2

 Cups and fluid ounces are common units of measurement for food items. Sometimes,
when a recipe calls for an item measured in cups, you find that in the grocery store the
item is sold in fluid ounces. To know how much you need to purchase for the recipe,
you need to convert the required number of cups to fluid ounces. The formula is:
Ounces = Cups × 8
 Create an application with a form similar to the one shown in the figure on the next
slide.
 The user enters the number of cup(s) into text box. When the user clicks the Convert
button, the application should display the equivalent value of Ounces in a Label field.

38
Figure for Question 2 39
Question 3
 Kinetic Energy
 In physics, an object that is in motion is said to have kinetic energy. The following
formula can be used to determine a moving object’s kinetic energy:

 In the formula KE is the kinetic energy, m is the object’s mass in kilograms, and v is
the object’s velocity in meters per second. Create an application that allows the user
to enter an object’s mass and velocity and then displays the object’s kinetic energy.
The application should have a method named KineticEnergy that accepts an object’s
mass (in kilograms) and velocity (in meters per second) as arguments. The method
should return the amount of kinetic energy that the object has. 40

You might also like