0% found this document useful (0 votes)
30 views

STD511 C# Programming: Methods, Classes and Objects

Here are programs to solve the exercises: 1. Read two integers and print their sum using a method: static void Main(string[] args) { int num1, num2; Console.Write("Enter first number: "); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter second number: "); num2 = Convert.ToInt32(Console.ReadLine()); PrintSum(num1, num2); } static void PrintSum(int a, int b) { int sum = a + b; Console.WriteLine("Sum is: " + sum); } 2. Read an

Uploaded by

WilliamSStephen
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)
30 views

STD511 C# Programming: Methods, Classes and Objects

Here are programs to solve the exercises: 1. Read two integers and print their sum using a method: static void Main(string[] args) { int num1, num2; Console.Write("Enter first number: "); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter second number: "); num2 = Convert.ToInt32(Console.ReadLine()); PrintSum(num1, num2); } static void PrintSum(int a, int b) { int sum = a + b; Console.WriteLine("Sum is: " + sum); } 2. Read an

Uploaded by

WilliamSStephen
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/ 29

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;
Console.WriteLine("Sum from 1 to 10 is " + sum)

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
Console.WriteLine("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
Console.WriteLine("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)


{Console.WriteLine("Sum from 1 to 20 is " + sum(1, 10) );
Console.WriteLine("Sum from 20 to 30 is " + sum(20, 30) );
Console.WriteLine("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 ClassName.MethodName (e.g.,
TestMax.Max).

11
Passing
public static
Parameters
void nPrintln(String message, int n) {
• for (int i = 0; i < n; i++) Console.WriteLine(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)
Math.Sin(0) returns 0.0
• Tan(double a) Math.Sin(Math.PI / 6)
returns 0.5
• Acos(double a) Math.Sin(Math.PI / 2)
• Asin(double a) returns 1.0
Math.Cos(0) returns 1.0
• Atan(double a) Math.Cos(Math.PI / 6)
returns 0.866
Math.Cos(Math.PI / 2)
returns 0
Radians
toRadians(90) 23
Exponent Methods
• exp(double a) Examples:
Returns e raised to the power of
a. Math.exp(1) returns 2.71
Math.log(2.71) returns 1.0
• log(double a)
Math.pow(2, 3) returns 8.0
Returns the natural logarithm of a.
Math.pow(3, 2) returns 9.0
• log10(double a) Math.pow(3.5, 2.5) returns
Returns the 10-based logarithm of 22.91765
a. Math.sqrt(4) returns 2.0
Math.sqrt(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
System.Decimal 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
• https://www.geeksforgeeks.org/c-sharp-mat
h-class/

26
Min, Max, and Abs

• Max(a, b)and Examples:

• Min(a, b)
Math.Max(2, 3) returns 3
Returns the maximum or
minimum of two parameters. Math.Max(2.5, 3) returns
3.0
• Abs(a)
Math.Min(2.5, 3.6)
Returns the absolute value of the
returns 2.5
parameter.
Math.Abs(-2) returns 2
• random() Math.Abs(-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 Random.Next(), Random.NextBytes(), and
Random.NextDouble() methods.
• The Random.Next() method returns a random number,
• Random.NextBytes() returns an array of bytes filled with random
numbers,
• and Random.NextDouble() returns a random number between 0.0
and 1.0.
• Some examples are here
28
References
• C# Programming for Absolute Beginners;
Radek Vystavel.

• https://www.geeksforgeeks.org/csharp-progr
amming-language/

• https://docs.microsoft.com/en-us/dotnet/csh
arp/

You might also like