STD511 C# Programming
Methods, Classes and Objects
Defining Methods
A method is a collection of statements that
are
grouped together to perform an operation.
Define a method Invoke a method
return value method formal
modifier type name parameters
int z = max(x, y);
method
header public static int Max(int num1, int num2) {
actual parameters
int result; (arguments)
method
body if (num1 > num2) parameter list
result = num1;
else method
result = num2; signature
return result; return value
}
2
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
[Link]("Sum from 1 to 10 is " + sum)
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
[Link]("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
[Link]("Sum from 35 to 45 is " + sum);
3
Solution
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
public static void Main(String[] args)
{[Link]("Sum from 1 to 20 is " + sum(1, 10) );
[Link]("Sum from 20 to 30 is " + sum(20, 30) );
[Link]("Sum from 35 to 45 is " + sum(35, 45) );
}
4
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the
implementation
from the user.
• Reduce complexity.
5
Formal
Parameters
The variables defined in the method header are known as
formal parameters.
Define a method Invoke a method
return value method formal
modifier type name parameters
method num1 num2
header public static int Max(int , int ) {
actual parameters
int result; (arguments)
method
body if (num1 > num2) parameter list
result = num1;
else method
result = num2; signature
return result; return value
}
6
Actual
Parameters
When a method is invoked, you pass a value to the parameter.
This value is referred to as actual parameter or argument.
Define a method Invoke a method
return value method formal
modifier type name parameters
int z = max(x, y);
method
header public static int Max(int num1, int num2) {
actual parameters
int result; (arguments)
method
body if (num1 > num2) parameter list
result = num1;
else method
result = num2; signature
return result; return value
}
7
Return Value
Type
A method may return a value. The returnValueType is the data
type of the value the method returns. If the method does not return
a value, the returnValueType is the keyword void.
Define a method Invoke a method
return value method formal
modifier type name parameters
int z = max(x, y);
method
header public static int Max(int num1, int num2) {
actual parameters
int result; (arguments)
method
body if (num1 > num2) parameter list
result = num1;
else method
result = num2; signature
return result ; return value
}
8
Calling Methods
• Testing the max method
• A program demonstrates calling a method
max to
• return the largest of the int values
9
Calling Methods, cont.
pass the value of i
pass the value of j
10
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The Max
method can be invoked from any class besides TestMax. If
you create a new class Test, you can invoke the Max
method using [Link] (e.g.,
[Link]).
11
Passing
public static
Parameters
void nPrintln(String message, int n) {
• for (int i = 0; i < n; i++) [Link](message);
•}
• Suppose you invoke the method using
• nPrintln(“Welcome to C#”, 5);
• What is the output?
• Suppose you invoke the method using
• nPrintln(“Computer Science”, 15);
• What is the output?
• Can you invoke the method using
• nPrintln(15, “Computer Science”); 12
Overloading Methods
Overloading the Max
Method
public static double Max(double num1,
double num2)
{ if (num1 >
num2)
return
else num1;
return
} num2;
13
Scope of Local
• A localVariables
variable: a variable defined inside a method.
• Scope: the part of the program where the variable
can be referenced.
• The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must be
declared before it can be used.
14
Scope of Local Variables,
cont.
You can declare a local variable with the same name
multiple times in different non-nesting blocks in a
method, but you cannot declare a local variable twice
in nested blocks.
15
Scope of Local Variables,
cont.
public static void method1()
{
.
.
• for (int i = 1; i < 10; i++) {
The scope of •.
i •.
The scope of • int j;
j •.
}
•.
}
•.
16
Scope of Local Variables,
cont.
It is fine to declare i in two
non-nesting blocks It is wrong to declare i in
two nesting blocks
public static void method1() {
int x = 1; public static void method2() {
int y = 1;
int i = 1;
for (int i = 1; i < 10; i++) { int sum = 0;
x += i;
} for (int i = 1; i < 10; i++)
for (int i = 1; i < 10; i++) { } sum += i;
y += i;
} }
}
17
Scope of Local Variables,
// Finecont.
with no errors
public static void CorrectMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
18
Scope of Local Variables,
cont.
// With errors
public static void IncorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
19
Exercise
•
s
Write a program to read two integers and
use a method that prints their sum.
• Write a program to read an integer and use a
method that returns its square.
• Write a program to read an integer and use a
method that returns its factorial.
Exercise
•
s
Write a program that reads 10 integers and
finds number off evens and number of odds.
Use a function isEven to determine whether
the integer is even or odd.
The Math Class
• Comes under the System
namespace
• Class constants:
– PI
–E
• Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods 22
Trigonometric Methods
• Sin(double a) Examples:
• Cos(double a)
[Link](0) returns 0.0
• Tan(double a) [Link]([Link] / 6)
returns 0.5
• Acos(double a) [Link]([Link] / 2)
• Asin(double a) returns 1.0
[Link](0) returns 1.0
• Atan(double a) [Link]([Link] / 6)
returns 0.866
[Link]([Link] / 2)
returns 0
Radians
toRadians(90) 23
Exponent Methods
• exp(double a) Examples:
Returns e raised to the power of
a. [Link](1) returns 2.71
[Link](2.71) returns 1.0
• log(double a)
[Link](2, 3) returns 8.0
Returns the natural logarithm of a.
[Link](3, 2) returns 9.0
• log10(double a) [Link](3.5, 2.5) returns
Returns the 10-based logarithm of 22.91765
a. [Link](4) returns 2.0
[Link](10.5) returns 3.24
• pow(double a, double b)
Returns a raised to the power of
b.
• sqrt(double a)
Returns the square root of a.
24
Rounding Methods
• decimal Ceiling(Decimal x)
This function return the smallest integral value which will be
greater than or equal to x. The type of this method is
[Link] and return a decimal instead of an integral
type
• decimal Floor(Decimal x)
Returns the largest integral value less than or equal to the
specified number.
• decimal Round(Decimal x) or double
Round(Double x)
Rounds a value to the nearest integer or to the specified
number of fractional digits.
• Sqrt() -> Returns the square root of a given number
• Pow() -> Returns a specified number raised to a given power
25
More on Rounding Methods
• [Link]
h-class/
26
Min, Max, and Abs
• Max(a, b)and Examples:
• Min(a, b)
[Link](2, 3) returns 3
Returns the maximum or
minimum of two parameters. [Link](2.5, 3) returns
3.0
• Abs(a)
[Link](2.5, 3.6)
Returns the absolute value of the
returns 2.5
parameter.
[Link](-2) returns 2
• random() [Link](-2.1) returns
Returns a random double value 2.1
in the range [0.0, 1.0).
The Random Class
• C# Random class provides functionality to generate random
numbers in C#. The Random class can also generate other data
types including strings.
• Random class constructors have two overloaded forms. It takes
either no value or it takes a seed value.
• The Random class provides [Link](), [Link](), and
[Link]() methods.
• The [Link]() method returns a random number,
• [Link]() returns an array of bytes filled with random
numbers,
• and [Link]() returns a random number between 0.0
and 1.0.
• Some examples are here
28
References
• C# Programming for Absolute Beginners;
Radek Vystavel.
• [Link]
amming-language/
• [Link]
arp/