You are on page 1of 8

Unit 1

User-Defined Functions

Introduction
In C#, a function is a way of packaging code that does something and then
returns the value. Unlike in C, C++ and some other languages, functions do
not exist by themselves. They are part of an object-oriented approach to
programming.A program to manage spreadsheets might include a sum()
function as part of an object, for example.
There are two types of function. Predefined or built-in functions are those that
are part of the C# library. These are present in any of the various headers that
can be included in a program. If your need these functions, just call them
anywhere in your main method or inside other methods or user-defined
functions. On the other hand, User-defined functions are programmed
routines that have its parameters set by the user of the system. User- defined
functions often are seen as programming shortcuts as they define functions
that perform specific tasks within a larger system.

In this unit, we will focus on discussing user-defined functions. You will learn
how to create, define, and call this type of function in our C# programs.

Unit Learning Outcome

 Write clean and maintainable code using user-defined functions.


 Solve programming problems using user-defined functions.

Topic: User-Defined Functions


Time Allotment: 8 hours lecture, 12 hours lab.

Learning Objectives

At the end of this session, students will be able to:


 Understand parameters and return values
 Write clean functions
 Test functions
 Debug functions
 Call functions within themselves
Activating Prior Knowledge

In C# programming, is it possible to decompose a large program into small


segments which makes program easy to understand, maintain and debug in
order to avoid repetition of codes?

Presentation of Contents

What is a Function?

A function is a named, independent section of C# code that performs a


specific task and optionally returns a value to the calling program.
SYNTAX:
<access_modifier> <return_type> <function_name>
(parameters)
{
body
}

Access modifiers are keywords used to specify accessibility of a member or a


type. An access modifier allows us a way to handle which member or type has
an access or not has an access to certain features in a program.

The function return type specifies the data type that the function returns to the
calling program. The return type can be of C#’s data types: char, int, long,
float, or double. You can also define a function that doesn’t return a value, a
return type of void. Here are some examples:

int func1(. . .) /* return a type int */


float func2(. . .) /* return a type float */
void func3(. . .) /* returns nothing */

You can name a function anything you like, as long as you follow the rules for
C# variable names. A function name must be unique (not assigned to any
other function or variable). It’s a good idea to assign a name that reflects what
the function does.

Many functions use arguments, which are values passed to the function when
it is called. A function needs to know what kind of arguments to expect – the
data type of each argument. You can pass a function any of C#’s data types.
Argument type information is provided in the function header by the parameter
list. To pass arguments to a function, you list them in parenthesis following the
function name. The number of arguments and the type of each argument
must match the parameters in the function header. For example, if a function
is defined to take two type int arguments, you must pass it exactly to int
arguments – no more, no less – and no other type. If the function takes
multiple arguments, the arguments listed in the function call are assigned to
the function parameters in order: the 1stargument to the 1 st parameter, the 2nd
argument to the 2nd parameter, and so on.

A parameter is an entry in a function header; it serves as a “place holder” for


an argument. A function’s parameters are fixed; they do not change during
program execution.

An argument is an actual value passed to the function by the calling program.


Each time a function is called, it can be passed different arguments.

Where to Put Functions?

You may be wondering where in your source code you should place your
function definitions. The basic structure of a program that uses functions is
shown below:

/* start of source code */


...
function1( )
{
...
}
function2( )
{
...
}
static void Main(string [] args)
{
...
}
/* end of source code */

How a Function Works?

A C# program does not execute the statements in a function until the function
is called by another part of the program. When a function is called, the
program can send information in the form of one or more arguments. An
argument is program data needed by the function to perform its task. The
statements then in a function execute, performing whatever task each was
designed to do. When the function’s statements have finished, execution
passes back to the same location in the program that called the function.
Functions can send information back to the program in the form of a return
value.

To return a value from a function, you use the keyword return, followed by a
C# expression. When execution reaches a return statement, the expression is
evaluated, and execution passes the value back to the calling program. The
return value of the function is the value of the expression.

Void and Parameterless Functions

A void function is used when input/output is to be performed and more than


one value is to be returned. A void function returns values by modifying one or
more parameters rather than using a return statement. A void function is
called by using the function name and the argument list as a statement in the
program.

A parameterless function is a function with empty parentheses. Empty


parentheses indicate that the function requires no parameters.

Example 1: Void and Parameterless Function

static public void PrintMyName() //function definition


{
Console.WriteLine(“Jose Protacio Rizal Mercado y Alonzo
Realonda”);
}

static void Main(string [] args)


{
PrintMyName(); //function call
Console.ReadKey(true);
}

When the above code is compiled and executed, it produces the following
result:

Jose Protacio Rizal Mercado y Alonzo Realonda

Functions with Return Value and Parameters

You can also add parameters in a function and a function can also return
values. A parameter is the symbolic name for "data" that goes into a function.
A function can take parameters which are just values you supply to the
function so that the function can do something utilizing those values. These
parameters are just like variables except that the values of these variables are
defined when we call the function and are not assigned values within the
function itself.

Parameters are specified within the pair of parentheses in the function


definition, separated by commas. When we call the function, we supply the
values in the same way. Note the terminology used - the names given in the
function definition are called parameters whereas the values you supply in the
function call are called arguments.

The specific value returned from a function is called the return value. When
the return statement is executed, the return value is copied from the function
back to the caller.

Example 2: With Return Value and Parameters

static int Sum(int x, int y)


{
return x + y;
}
static void Main(string [] args)
{
int number1 = 5;
int number2 = 10;
int total;
total = Sum(number1, number2);
Console.WriteLine(“Sum is: “ + total);
Console.ReadKey(true);
}

When the above code is compiled and executed, it produces the following
result:

Sum is: 15

Example 3: A program that will calculate the cube of a number

static long cube(long x)


{
long x_cube;
x_cube = x*x*x;
return x_cube;
}
static void Main(string [] args)
{
long input, answer;
Console.Write(“Enter an integer value: “);
input = Convert.ToInt64(Console.ReadLine());
answer = cube(input);
Console.WriteLine(“The cube of “ + input + “is “ + answer);
Console.ReadKey(true);
}

When the above code is compiled and executed, it produces the following
result:
Enter an integer value: 5
The cube of 5 is 125

Example 4: Finding Maximum Value

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;
return result;
}

static void Main(string[] args)


{
/* local variable definition */
int a = 100;
int b = 200;

int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Max value is: 200

Example 5: A method can call itself. This is known as recursion. Recursion is


made for solving problems that can be broken down into smaller, repetitive
problems. It is especially good for working on things that have many possible
branches and are too complex for an iterative approach. Following is an
example that calculates factorial for a given number using a recursive
function:

using System;
namespace CalculatorApplication
{
class NumberManipulator

{
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Factorial of 6 is: 720


Factorial of 7 is: 5040
Factorial of 8 is: 40320

You might also like