Unit-1-User-Defined-Functions IN COMPUTER PROGRAMMING

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Unit 1: User-Defined Functions

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

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


• write clean and maintainable code using user-defined functions;
• solve programming problems using user-defined functions.

Topic: User-Defined Functions


Time Allotment: 3 hours lecture, 6 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.

1
Unit 1: User-Defined Functions

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_specifier> <return_type> <function_name> (parameters)
{
body
}

Access specifiers 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

2
Unit 1: User-Defined Functions
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 1st 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

3
Unit 1: User-Defined Functions
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.

A function that does not return any value specifies void type as a return type.
In the following example, a function is created without return type.

Example 1: Void and Parameterless Function

using System;
namespace FunctionExample
{
class Program
{
// User defined function without return type
public void Show() // No Parameter
{
Console.WriteLine("This is non parameterized function");
// No return statement
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show(); // Calling Function
}
}
}

4
Unit 1: User-Defined Functions
When the above code is compiled and executed, it produces the following
result:

This is non parameterized function

Example 2: using parameter but no return type


using System;
namespace FunctionExample
{
class Program
{
// User defined function without return type
public void Show(string message)
{
Console.WriteLine("Hello " + message);
// No return statement
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show("Philippines"); // Calling Function
}
}
}

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

Hello Philippines

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.

5
Unit 1: User-Defined Functions
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 3: 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 4: 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);

6
Unit 1: User-Defined Functions
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 5: 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();
}
}
}

7
Unit 1: User-Defined Functions
When the above code is compiled and executed, it produces the following
result:

Max value is: 200

Example 6: 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();
}
}
}

8
Unit 1: User-Defined Functions
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

C# Call By Value

In C#, value-type parameters are that pass a copy of original value to the
function rather than reference. It does not modify the original value. A change
made in passed value does not alter the actual value. In the following example,
we have pass value during function call.

C# Call By Value Example


using System;
namespace CallByValue
{
class Program
{
// User defined function
public void Show(int val)
{
val *= val; // Manipulating value
Console.WriteLine("Value inside the show function "+val);
// No return statement
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
int val = 50;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before calling the function "+val);
program.Show(val); // Calling Function by passing value
Console.WriteLine("Value after calling the function " + val);
}
}
}

9
Unit 1: User-Defined Functions
Output:
Value before calling the function 50
Value inside the show function 2500
Value after calling the function 50

C# Call By Reference

C# provides a ref keyword to pass argument as reference-type. It passes


reference of arguments to the function rather than copy of original value. The
changes in passed values are permanent and modify the original variable
value.

C# Call By Reference Example


using System;
namespace CallByReference
{
class Program
{
// User defined function
public void Show(ref int val)
{
val *= val; // Manipulating value
Console.WriteLine("Value inside the show function "+val);
// No return statement
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
int val = 50;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before calling the function "+val);
program.Show(ref val); // Calling Function by passing reference

Console.WriteLine("Value after calling the function " + val);


}
}
}

10
Unit 1: User-Defined Functions
Output:
Value before calling the function 50
Value inside the show function 2500
Value after calling the function 2500

C# Out Parameter

C# provides out keyword to pass arguments as out-type. It is like reference-


type, except that it does not require variable to initialize before passing. We
must use out keyword to pass argument as out-type. It is useful when we want
a function to return multiple values.

C# Out Parameter Example 1


using System;
namespace OutParameter
{
class Program
{
// User defined function
public void Show(out int val) // Out parameter
{
int square = 5;
val = square;
val *= val; // Manipulating value
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
int val = 50;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before passing out variable " + val);
program.Show(out val); // Passing out argument
Console.WriteLine("Value after recieving the out variable " + val);
}
}
}

11
Unit 1: User-Defined Functions
Output:

Value before passing out variable 50


Value after receiving the out variable 25

The following example demonstrates that how a function can return multiple
values.

C# Out Parameter Example 2


using System;
namespace OutParameter
{
class Program
{
// User defined function
public void Show(out int a, out int b) // Out parameter
{
int square = 5;
a = square;
b = square;
// Manipulating value
a *= a;
b *= b;
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
int val1 = 50, val2 = 100;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before passing \n val1 = " + val1+" \n v
al2 = "+val2);
program.Show(out val1, out val2); // Passing out argument
Console.WriteLine("Value after passing \n val1 = " + val1 + " \n
val2 = " + val2);
}
}
}

12
Unit 1: User-Defined Functions
Output:
Value before passing
val1 = 50
val2 = 100
Value after passing
val1 = 25
val2 = 25

Reflection
As a BSIT/BSCS student, what do you think is the importance of learning how
to develop programs with the use of user-defined functions? Do you think it
gives you a lot of advantage most especially in solving complex problems?
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_________________________________________________________

• A function is a named, independent


section of C# code that performs a specific task and optionally returns
a value to the calling program.
• Access modifiers are keywords used to specify accessibility of a
member or a type.
• The function return type specifies the data type that the function
returns to the calling program.
• A parameter is an entry in a function header; it serves as a “place
holder” for an argument.
• An argument is an actual value passed to the function by the calling
program.
• To return a value from a function, you use the keyword return,
followed by a C# expression.
• Recursion is made for solving problems that can be broken down into
smaller, repetitive problems.

https://www.thoughtco.com/introduction-to-functions
https://www.learncpp.com/cpp-tutorial/function-return-values/
https://www.w3resource.com/
https://liucs.net/cs102f15/programming-rubric.pdf
https://openclassrooms.com/en/courses/5670356-learn-programming-with-c

13

You might also like