Search⌘ K
AI Features

Functions with Parameters and Return Values

Explore how to define and call functions with parameters and return values in C#. Understand passing arrays as parameters, creating value-returning functions, and practice with examples like multiplication tables, searching strings in arrays, and generating Fibonacci sequences.

Function with parameters

The parameters are the input values for the function enclosed in (), provided in the function call as arguments. Multiple parameters are separated by , and each parameter must have a data type.

static void showSum(int a, int b)
{
  System.Console.WriteLine(a + b);
}

The following function receives two int parameters and displays their sum.

showSum(5, 10);
C#
class Test
{
static void showSum(int a, int b)
{
System.Console.WriteLine(a + b);
}
static void Main()
{
showSum(5 , 10);
}
}

Array as a function parameter

An array can be received in a function as a parameter. The following program demonstrates the use of an array as a function parameter.

C#
class Test
{
static void getSum(int[] nums)
{
int c = 0;
for (int i = 0 ; i < nums.Length; i++)
{
c += nums[i];
}
System.Console.WriteLine(c);
}
static void Main()
{
int[] nums = {10, 20, 30, 40};
getSum(nums);
}
}

In the program above, the function receives an array int[] nums as a parameter. We need the size to traverse through each element of the array using arr.Length. We have used a for loop to calculate the sum of array elements ...