Lesson # 5. Methods or Functions in C sharp

Programming on c sharp in Microsoft Visual Studio. Using methods or functions.

Lesson # 5. Theory

Keyboard Shortcuts for running and debugging

    Ctrl + F5 to run the application without debugging
    F5 to run the application in the debug mode
    Shift + F5 to stop the debugging session
    F9 to insert or remove a breakpoint
    F10 to step over a method (while debugging)
    F11 to step into a method (while debugging)
    Ctrl + Shift + F5 to restart debugging
    Shift + F11 to step out of a method (while debugging)

Declaring Methods or Functions

  • Methods allow us to encapsulate behavior and functionality within the objects that we create in our code.
  • A method is declared using a method signature and method body.
  • Signature consists of:
    Access modifier — from where the method can be called. There are some of them:

  • private — most restrictive and allows access to the method only from within the containing class or struct
  • public — allowing access from any code in the application
  • protected — allows for access from within the containing class or from within derived classes
  • internal — accessible from files within the same assembly
  • static — indicates the method is a static member of the class rather than a member of an instance of a specific object.
  • Return type — used to indicate what type the method will return. Use void if the method will not return a value or any supported data type
  • Method name — all methods need a name so you know what to call in code. Identifier rules apply to methods names as well
  • Parameter list — a comma separated list of parameters to accept arguments passed into the method
  • Sample method:

    public Boolean StartService(string serviceName)
    {
       // code to start the service
    }

    In the example:
    public is the access modifier,
    Boolean is the return type,
    StartService is the name,
    string serviceName is the parameter list.

  • To return a value from a function, use the operator:
  • return expression;
  • If we have void instead of the return type, so it means that the function will not return any value.
  • static void SayHello()
    {
     Console.WriteLine("Hello");
    }
  • You can define a function in the same class as the Main () function, or you can define it in a different class.
  • All methods or functions must be static, which means that you can call it without creating a class of the object.
  • To make methods (functions) described in the same class visible in another, they should be described with the public access modifier.
  • If the method (function) is called in the same class, the public access modifier is not required.

Calling a Method

  • To call a method, you specify the method name and provide any arguments that correspond to the method parameters in parentheses.
  • static void Main(string[] args)
            {
                int res;
                Square(5, out res);
                Console.WriteLine(res);  
            }
            static void Square(int a, out int res)
            {
                res = a * a;
            }

    In the example:
    aref argument;
    resout argument.

    Returning Data from Methods

    There are three approaches (подхода) that you can use:

  • Return an array or collection
  • Use the ref keyword
  • Use the out keyword
  • Arguments are divided into out and ref arguments. Out — output, ref — input-output.
  • ref arguments must be initialized before calling the function, otherwise it is an error. When calling, the out and ref keywords are also specified.
  • The parameters for this method use the out keyword to indicate that values will be returned for these parameters:
  •  static void Main(string[] args)
            {
     
                int first;
                String sValue;
                ReturnMultiOut(out first, out sValue);
                Console.WriteLine($"{first.ToString()}, {sValue}");
            }
            static void ReturnMultiOut(out int i, out string s)
            {
                i = 25;
                s = "using out";
            }

    The result will be:

    25 using out 
  • In this new code example, the keyword ref is used to return multiple values from the method. Typically the ref keyword requires that the variables being used are initialized first.
  •  static void Main(string[] args)
            {
                // Using ref requires that the variables be initialized first
                int first =0;
                String sValue="";
                ReturnMultiOut(ref first, ref sValue);
                Console.WriteLine($"{first.ToString()}, {sValue}");
     
            }
            static void ReturnMultiOut(ref int i, ref string s)
            {
                i = 25;
                s = "using out";
            }

    Labs and tasks

    Lab 1. Functions

    To do: Create Sum() method that takes two integer arguments and sums them. The method returns no value (which is why you have to use void).

    Note: We need to use static in the method signature because the Main function is static and we cannot call a non-static method from a static method.

    [Solution and Project name: Lesson_5Lab1, file name L5Lab1.cs]

    The resulting examples:

    Please enter two numbers
    20 40 
    The sum of 20 and 40 is: 60
    


    ✍ Algorithm:

    • Open Visual Studio.
    • Create Console Application with the name Lesson_5Lab1: File -> New -> Project/Solution -> Console Application.
    • In the Solution Explorer window find a file Program.cs and rename it into L5Lab1.cs.
    • In the Main function request the user to input two numbers:
    • ...
      Console.WriteLine("Please enter two numbers");
      int a = int.Parse(Console.ReadLine());
      int b = int.Parse(Console.ReadLine());
      ...
      
    • Place your cursor after the closing curly brace of the static void Main(string[] args) function and press enter. We are doing this because you don’t want to place methods/functions inside another function.
    • Declare a new method called Sum() that will be used to add values passed into it:
    • ...
      static void Sum(int first, int second)
      {
          int sum = first + second;
          Console.WriteLine($"The sum of {first} and {second} is: {sum}");
      }
      ...
      
    • Now we can call this method from within the Main function. Enter the following code within the curly braces of Main():
    • static void Main(string[] args)
              {
                  ...
                  Sum(a, b);
              }
    • Press the CTRL+F5 keys to start the application without debugging.
    • The function Sum() we’ve created doesn’t return a value. We will now modify that method so that it returns the result to the calling method.
    • Comment the code of the Sum() function using the shortcut key [CTRL]+k+c:
    • //static void Sum(int first, int second)
      //{
      //    int sum = first + second;
      //    Console.WriteLine($"The sum of {first} and {second} is: {sum}");
      //}
    • Place your cursor after these comments and enter the following code:
    • ...
      static int Sum(int first, int second)
         {
            int sum = first + second;
            return sum;
          }
      ...
      
    • The method returns an integer value which is why we use int in the signature (static int Sum(...)).
    • Then we need to modify the code in Main(). Declare an integer variable to receive the return value. Print out the result to the console window.
    • ...
      static void Main(string[] args)
        {
           int result = Sum(a, b);
           Console.WriteLine($"The sum of {a} and {b} is {result}");
        }
      ...
      
    • Run the application again and check the output. Both outputs should be the same.
    •   
      Overloading the method (function):

    • Let’s now overload our Sum() method. To do it we will create two additional methods with the same names.
    • Place your cursor after the Sum() method code. First, create a method that accepts three integers by entering the following code:
    • static int Sum(int first, int second, int third)
      {
          int sum = first + second + third;
          return sum;
      }
      
    • This method uses the same name as the Sum() method that takes two integers, but the parameters here indicate the method is expecting three integers as arguments. The compiler knows which method to call based on the number of arguments passed in.
    • Next, enter the following code that will create a Sum() method that accepts two doubles as arguments:
    • ...
      static double Sum(double first, double second)
      {
          double result = first + second;
          return result;
      }
      ...
      
    • This method uses the same name as the Sum() method that takes two integers, but the parameters here indicate the method is expecting two doubles as arguments. The compiler knows which method to call based on the arguments data types.
    • Finally, modify the code in Main() that calls the methods:
    • static void Main(string[] args)
      {   
          ...
          int result = Sum(a, b);
          Console.WriteLine($"Calling Sum() with two arguments, result is: {result}");
      
          int result3 = Sum(10, 50, 80);
          Console.WriteLine($"Calling Sum() with three arguments, result is: {result3}");
      
          double dblResult = Sum(20.5, 30.6);
          Console.WriteLine($"Calling Sum() that takes doubles result in: {dblResult}");
      }
      
    • Run the application again and check the output. You should see the correct summed values displayed for each call of the three different methods. Even though they are all named Sum, the compiler works out the correct method to call based on the method signature. That is how the method overloading works.
    • To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_5Lab1\) and upload the file L5Lab1.cs.

    Task 1 for Lesson #5:

    To do: Three numbers are inputted, they are the lengths of the triangle’s three sides. Create a Perimeter function that calculates the perimeter of a triangle based on the lengths of its three sides.
      
    Note 1: Perimeter() method must take three integers as arguments.
    Note 2: The method must return no value which is why you have to use void in the signature:

    static void Perimeter(...);

    Note 3: Don’t forget to convert the inputted values into integers. For example:

    int a = int.Parse(Console.ReadLine());

      
    [Solution and Project name: Lesson_5Task1, file name L5Task1.cs]
      
    The resulting example:

    Please enter the 3 sides of the triangle:
    3 5 6
    The perimeter is: 14
    

    Task 2 for Lesson #5:

    To do: You have to remake the previous task, now the function Perimeter must return an integer value. We remind you of the task: Three numbers are inputted, they are the lengths of the triangle’s three sides. Create a Perimeter function that calculates the perimeter of a triangle based on the lengths of its three sides.
      
    Note 1: Perimeter() method must take three integers as arguments.
    Note 2: The method must return an integer value which is why you have to use int in the signature:

    static int Perimeter(...);

    Note 3: Don’t forget to convert the inputted values into integers:

    int a = int.Parse(Console.ReadLine());

      
    [Solution and Project name: Lesson_5Task2, file name L5Task2.cs]
      
    The resulting example:

    Please enter the 3 sides of the triangle:
    3 5 6
    The perimeter is: 14
    

    Task 3 for Lesson #5:

    To do: Create a Distance function that calculates a distance between two points on the plane, the coordinates of the points are inputted (variables x1,y1 for the first point and x2,y2 for the second).
      
    Note 1: Distance() method must take four integers as arguments.
    Note 2: The method must return no value which is why you have to use void in the signature:

    static void Distance(...);

    Note 3: To calculate the distance between two points you have to use the formula:

    square root: Math.Sqrt(...);
    the power of a number: Math.Pow(number, power);

      
    [Solution and Project name: Lesson_5Task3, file name L5Task3.cs]
      
    The resulting example:

    Please enter the coordinates of two points (four integers: x1, y1, x2, y2):
    1 -2  4  2
    The distance is: 5
    

    Task 4 for Lesson #5:

    To do: You have to remake the previous task, now the function Distance must return a double value. We remind you of the task: Create a Distance function that calculates a distance between two points on the plane, the coordinates of the points are inputted (variables x1,y1 for the first point and x2,y2 for the second).
      
    Note 1: Distance() method must take four integers as arguments.
    Note 2: The method must return a double value which is why you have to use double in the signature:

    static double Distance(...);

    Note 3: To calculate the distance between two points you have to use the formula:

    square root: Math.Sqrt(...);
    the power of a number: Math.Pow(number, power);

      
    [Solution and Project name: Lesson_5Task4, file name L5Task4.cs]
      
    The resulting example:

    Please enter the coordinates of two points (four integers: x1, y1, x2, y2):
    1 -2  4  2
    The distance is: 5
    

    Lab 2. Ref arguments (input-output arguments)

    To do: Create Minmax() method that takes two integer arguments by reference and change their values so that the first parameter is always greater than the second one (changing their values so that the first parameter has a minimum, and the second one has a maximum value). Create an overloaded Minmax function for three parameters.

    Note 1: We need to use static in the method signature because the Main function is static and we cannot call a non-static method from a static method.

    Note 2: The method returns no value (which is why you have to use void in signature). ref arguments are input-output arguments, which means that their values are changed within the method and passed from within the method to the main program.

    [Solution and Project name: Lesson_5Lab2, file name L5Lab2.cs]

    The resulting examples:

    Please enter two numbers
    2 4 
    After Mimax the result is: 4 2
    Please enter three numbers
    2 4 3
    After overloaded Mimax the result is: 4 3 2
    


    ✍ Algorithm:

    • Create Console Application with the name Lesson_5Lab2.
    • In the Solution Explorer window find a file Program.cs and rename it into L5Lab2.cs.
    • In the Main function request the user to input two numbers. Assign inputted values to the variables:
    • ...
      Console.WriteLine("Please enter two numbers");
      int a = int.Parse(Console.ReadLine());
      int b = int.Parse(Console.ReadLine());
      ...
      
    • After this, just under the entered code, you have to add the same code for overloaded function with three arguments. So you must request the user to input three numbers. Assign inputted values to the variables:
    • ...
      Console.WriteLine("Please enter three numbers");
      a = int.Parse(Console.ReadLine());
      b = int.Parse(Console.ReadLine());
      int c = int.Parse(Console.ReadLine());
      ...
      
    • Now we will create our function (method). Place your cursor after the closing curly brace of the static void Main(string[] args) function and press enter. We are doing this because you don’t want to place methods/functions inside another function.
    • Declare a new method called Minmax() that will be used to exchange values passed into it if it is needed. Use the ref keyword for arguments:
    • ...
      static void Minmax(ref int a, ref int b)
      {
          ...
      }
      ...
      
    • The keyword ref is used to indicate that value will be taken into the method from the main function and will be returned from the method.
    • Find a maximum and minimum of two inputted numbers using Min() and Max() standard functions. Set the results to the variables:
    • static void Minmax(ref int a, ref int b)
              {
                  int max = Math.Max(a, b);
                  int min = Math.Min(a, b);
                  ...
              }
      
    • After this, assign the values of the new variables to a and b variables in such a way that a variable has a maximum value and b — a minimum:
    • ...
          a = min;
          b = max;
      ...
      
    • We don’t need to return any values from the Minmax function, because we return the values using the ref keyword.
    • Now we can call this method from within the Main function and output the result. Enter the following code within the curly braces of Main(), just before the line Console.WriteLine("Please enter three numbers");:
    • ...
       Minmax(ref a,ref b);
       Console.WriteLine($"After Minmax the result is: {a}, {b}");
       Console.WriteLine("Please enter three numbers"); // this is the previous code
      ...
      
    • Run the application and check the output.
    • To collapse the code of the method for a while you can use Ctrl+M (twice). To expand it again use the same shortcut snippet Ctrl+M (twice).
    • Overloading the method (function):

    • Let’s now overload our Minmax() method. To do it we will create an additional method with the same name.
    • Place your cursor after the Minmax() method code. Create a method that accepts three integers:
    • ...
       static void Minmax(ref int a, ref int b, ref int c)
              {
                  Minmax(ref a, ref b);
                  Minmax(ref b, ref c);
                  Minmax(ref a, ref b);
              }
      ...
      
    • Within this method we use the first our Minmax() method to find a minimum and maximum of a and b variables, then of b and c, and after this — of a and b variables (because b has another value to this moment, the middle value).
    • This method uses the same name as the Minmax() method that takes two integers, but the parameters here indicate the method is expecting three integers as arguments. The compiler knows which method to call based on the number of arguments passed in.
    • Finally, modify the code in Main() that calls the method with three parameters:
    • ...
       Minmax(ref a,ref b, ref c);
       Console.WriteLine($"After overloaded Minmax the result is: {a}, {b}, {c}");
      ...
      
    • Run the application again and check the output. You should see the correct results for each call of the two different methods. Even though they equal names, the compiler works out the correct method to call based on the method signature. That is how the method overloading works.
    • To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_5Lab2\) and upload the file L5Lab2.cs.

    Task 5 for Lesson #5:

    To do: A two-digit integer is inputted. Create ChangeDigits() method that takes an inputted argument by reference and changes its value so that the first digit of a new number is the second digit of the inputted number, and vice versa, the second digit of a new number is the first digit of the inputted number. For example, if 45 is inputted, the resulting number will be 54.
      
    Note 1: ChangeDigits() method must take an integer by reference as an argument.
    Note 2: The method doesn’t return any value, which is why you have to use void in the signature:

    static void ChangeDigits(...);

    Note 3: First, you have to get the digits of the number. Then, you have to make a number of the resulting digits replacing them. To make a number of two digits use the example:

    if we have 2, 3
    2*10 + 3 = 23
    

      
    [Solution and Project name: Lesson_5Task5, file name L5Task5.cs]
      
    The resulting example:

    Please enter two-digit number:
    58
    The result is: 85
    

    Task 6 for Lesson #5:

    To do: Two two-digit integers are inputted. Create a BitwiseSum function that calculates their bitwise (поразрядный) sum modulo 10. For example, the bitwise sum of the numbers 34 and 59 is the number 83 (3 + 5 = 8; 4 + 9 = 13, 13%10 = 3).
      
    Note 1: BitwiseSum() method must take two integers as arguments.
    Note 2: The method must return an integer value which is why you have to use int in the signature:

    static int BitwiseSum(...);

    Note 3: First, you have to get the digits of the number. Then, to calculate the bitwise sum modulo 10 of the digits. Afterward, you have to make a number of the resulting digits. To make a number of two digits use the example:

    if we have 2, 3
    2*10 + 3 = 23
    

      
    [Solution and Project name: Lesson_5Task6, file name L5Task6.cs]
      
    The resulting example:

    Please enter two two-digit numbers:
    34 59
    The bitwise sum of 34 and 59 is: 83
    

    Lab 3. Ref arguments (input-output arguments)

    To do: Create MinmaxSeq() method that takes two integer arguments by reference, they are minimum and maximum values of the inputted sequence. User must input the sequence of integers and finish the inputting by entering 0. The method has to find a minimum and maximum and them to the main function.

    Note 1: The method returns no value (which is why you have to use void in signature). ref arguments are input-output arguments, which means that their values are changed within the method and passed from within the method to the main program.
    Note 2: We need to use static in the method signature because the Main function is static and we cannot call a non-static method from a static method.

    [Solution and Project name: Lesson_5Lab3, file name L5Lab3.cs]

    The resulting examples:

    Please enter the sequence, input 0 when it ends
    2  4  8  3  0
    minimum is: 2, maximum is: 8
    


    ✍ Algorithm:

    • Create Console Application with the name Lesson_5Lab3.
    • In the Solution Explorer window find a file Program.cs and rename it into L5Lab3.cs.
    • In the Main function declare two variables — to store a minimum and maximum values. Assign them the start values: for min variable the start value has to be the greatest value among integers, for max the start value has to be the smallest value within all the integers:
    • ...
      int max = int.MinValue;
      int min = int.MaxValue;
      ...
      
    • Our function/method will have the name MinmaxSeq() and it will take two arguments by reference — the variables min and max. First let’s call our method from within the Main function, just under initializations of min and max:
    •   int max = int.MinValue;
        int min = int.MaxValue;
        MinmaxSeq(ref max, ref min); // new code
      
    • C# can add the signature of the functions itself. Let’s ask it to do it. You have to hover the mouse above the calling of the function and click on the arrow next to the light bulb:
    • Click on the phrase «Generate method…». After, we have the ready signature for our method:
    • Clear the line inside of the function out.
    • Now we have to write down the code of the function. At first, we must request the user to input the sequence.
    • In order not to print always the classes Console and Math out, we can include them right in the beginning of the editor window:
    • Since now you don’t need to print Console.ReadLine() or Console.WriteLine(...), it is enough to print just ReadLine() or WriteLine(...).
    • Request the user:
    • ...
        private static void MinmaxSeq(ref int max, ref int min)
              {
                  WriteLine("Please enter the sequence, input 0 when it ends");
              }
      ...
      
    • To input the numbers of the sequence we will create the do..while loop:
    •     int a;
          do
          {
             a = Int32.Parse(ReadLine());
          }
          while (a != 0);
      
    • Within the loop, check to see if the value of variable a is maximum or minimum and reassign the values of max and min.
    •    ...
         if (a > max && a != 0) { max = a; }
         else if (a < min && a != 0) { min = a; }
         ...
      
    • All we have to do now, it is to output the values of min and max in the Main function:
    • Run the application and check the output.
    • To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_5Lab3\) and upload the file L5Lab3.cs.

    Task 7 for Lesson #5:

    To do: Create PosNegSeq() method that takes two integer arguments by reference, they are counters for positive and negative values of the inputted sequence. User must input the sequence of integers and finish the inputting by entering 0. The method has to count positive and negative of the inputted numbers and return the values of counters to the main function.

    Note 1: The method returns no value (which is why you have to use void in signature). ref arguments are input-output arguments, which means that their values are changed within the method and passed from within the method to the main program.
    Note 2: A ref arguments have to be initialized before the calling of the function. So, first, you have to do is to initialize the arguments. The start value for the counters — the arguments of the function — is 0:

    ...
    int counterPositive = 0;
    int counterNegative = 0;
    ...

      
      
    [Solution and Project name: Lesson_5Task7, file name L5Task7.cs]
      
    The resulting example:

    Please enter the sequence, input 0 when it ends
    2  -4  8  -3  5  0
    counter for positive is: 3, counter for positive is: 2
    

    Extra tasks

    Extra Task 1 for Lesson #5:

    To do: Create a FloorCubicRoot function that finds the largest integer that does not exceed the cubic root of the specified number (Math.Pow, Math.Floor).

    Note: You can calculate the cubic root of the number x in the wolframalpha service using the query x1/3, for example: 15.6251/3 (the answer is 2.5).
      
    [Solution and Project name: Lesson_5ExTask1, file name L5ExTask1.cs]
      
    The resulting example:

    Please enter a number:
    1/3
    The number is 2.5 : 15.625 ^ 1/3
    


    Extra Task 2 for Lesson #5:

    To do: A real number A and an integer N (≥ 0) are inputted. Create a function SumOfSeq() which finds the sum of:

    1 + A + A2 + A3 + ... + AN
    

    Note 1: Within a function, there has to be the only loop.

    Note 1: Do not use standard pow function for the degree, accumulate the values of degrees using a loop.

     [Solution and Project name: Lesson_5ExTask2, file name L5ExTask2.cs]
      
    The resulting example:

    Please enter a double A and an integer N:
    2.2  3
    Sum of elements of the sequence of powers of the number 2.2 from 0 to 3: 18.688
    

    Поделитесь уроком с коллегами и друзьями:[SvenSoftSocialShareButtons]

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    *
    *


    Вставить формулу как
    Блок
    Строка
    Дополнительные настройки
    Цвет формулы
    Цвет текста
    #333333
    Используйте LaTeX для набора формулы
    Предпросмотр
    \({}\)
    Формула не набрана
    Вставить