Lesson # 5. Methods or Functions in C sharp

Дата изменения: 9 апреля 2021
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)
    Ctrl + m + m to collapse a methods code while your cursor is at some place of this code. To expand it use the same keyboard shortcut (while your cursor is at some place of the methods signature)

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 ref keyword is also specified.
  • Take a look at the following two examples: the first one without ref, the second one with ref keyword:
  • // 1. without ref
    static void Main(string[] args)
            {
                int a = 1;
                Plas2(a);
                Console.WriteLine(a); // the result is 1
            }
    static void Plas2(int a)
            {
                a += 2;
            }
    // 2. with ref
    static void Main(string[] args)
            {
                int a = 1;
                Plas2(ref a);
                Console.WriteLine(a); // the result is 3
            }
    static void Plas2(ref int a)
            {
                a += 2;
            }
  • The parameters use the out keyword to indicate that values will be returned for these parameters. When calling, the out keywords are also specified:
  • static void Main(string[] args)
            {
                int a; // we shouldn't set any value to it down here 
                Plas2(out a);
                Console.WriteLine(a); // 3
            }
    static void Plas2(out int a)
            {
                a = 1; // we have to set some value to it
                a += 2;
            }
  • One more example with out modifier:
  •  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";
            }

    Overloading methods

    • Having a method with the same name but different signatures.

    Labs and tasks

    Console applications

    Lab 1. Function that sums two arguments

    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 keyword 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}");
      }
      ...
      
      The method doesn’t return any value to the main program, which is why we have to use void keyword.
      The method returns a sum of two values passed in.
    • 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 (to the Main method from where it was called).
    • 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(...)).
      Notice that the parameters’ names we have specified here in the method may not match the names of the arguments we have passed in. They become local variables within the scope of this method.
    • Then we need to modify the code in Main(). We have to change the way to call the method. 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):

      Overloading Methods means having a method with the same name but different signatures.
    • 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:

    To do: Three numbers are entered, 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 accept 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 entered values into integers. For example:

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

      
    Expected output:

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

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

    Task 2:

    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 entered, 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 accept 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 entered values into integers:

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

      
    Expected output:

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

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

    Lab 2. Building an Exponent Function

    To do: Create GetPow() method that takes two integer arguments, they are base number and power number. The method returns the result of taking a base number to power number.

    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 function returns an integer value, which is why you have to use int in the signature of the function:

    static int GetPow(int baseNum, int powNum) {}

    Expected output:

    Please enter two numbers – a base number and a power number:
    2  4 
    Base number 2 raised to the power number 4 = 16
    

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

    ✍ Algorithm:

    • Open Visual Studio.
    • Create Console Application with the name Lesson_5Lab2: File -> New -> Project/Solution -> Console Application.
    • After a closing curly brace of the Main function type the signature of the GetPow function:
    • static int GetPow(int baseNum, int powNum) {…}
      The function expects two integer numbers – baseNum argument and powNum argument. Inside the function, we’re going to take the baseNum to the power of powNum.
    • Declare a variable result to return its value from the function as a result.
    • int result = 1;
      …
      return result;
    • Inside the function create a for loop to keep multiplying result variable to baseNum powNum times:
    • for (int i=0; i<powNum; i++)
      {
      result = result * baseNum;
      }
      The first time we go through the loop we always have 1 * baseNum and store the result in the result variable. The second time we have baseNum * baseNum. The third – baseNum * baseNum * baseNum, etc. We repeat it each iteration.
    • Within the Main function call the method:
    • Console.WriteLine("Base number {baseNum} raised to the power number {powNumNum}  = {GetPow(2,4)} ");
    • Run the application and check the output.
    • Instead of the particular numbers (2 and 4) prompt the user input two numbers and change the code of the calling the function:
    • Console.WriteLine ("Please enter two numbers – a base number and a power number: ");
      int a = Int32.Parse(Console.ReadLine());
      int b = Int32.Parse(Console.ReadLine());
      Console.WriteLine(GetPow(a,b));
    • Run the application again and check the output.
    • Save and upload the file into the moodle system.

    🎦

    If you don’t understand something you can watch the explanation. I’m sorry for my English:)


    Task 3:

    To do: Create a Distance function that calculates a distance between two points on the plane, the coordinates of the points are entered (the variables x1,y1 for the first point and x2,y2 for the second).
      
    Note 1: The Distance() method must accept four integers as arguments (the coordinates of the points).

    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);

      
    Expected output:

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

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

    🎦

    If you have some questions you can watch this video with some tips:

    Task 4:

    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 entered (variables x1,y1 for the first point and x2,y2 for the second).
      
    Note: The method must return a double value which is why you have to use double in the signature:

    static double Distance(...);

      
    Expected output:

    Please enter the coordinates of two points (four integers: x1, y1, x2, y2):
    3.2   3.4  8  7.1  
    The distance is: 6.0605
    

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

    Lab 3. 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 maximum, and the second one has a minimum 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.

    Expected output:

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

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

    ✍ 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 request the user to input two numbers. Assign entered 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 entered 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 modifier ref is used to indicate that value will be taken into the method from the main function and will be returned from the method. Ref arguments must be initialized before calling the function, otherwise, it is an error. When calling, the ref keyword is also specified.
    • Find a maximum and minimum of two entered numbers using Min() and Max() standard functions:
    • static void Minmax(ref int a, ref int b)
              {
                  int max = Math.Max(a, b);
                  int min = Math.Min(a, b);
                  ...
              }
      
    • 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 = max;
        b = min;
      
    • 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_5Lab3\) and upload the file L5Lab3.cs.

    Task 5:

    To do: A two-digit integer is entered. Create ChangeDigits() method that takes an entered argument by reference and changes its value so that the first digit of a new number is the second digit of the input number, and vice versa, the second digit of a new number is the first digit of the input number. For example, if 45 is entered, the resulting number will be 54.
      
    Note 1: The 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 by swapping them. To make a number of two digits use the example:

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

      
    Expected output:

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

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

    🎦

    You can watch the video with come hints of making the task:

    Task 6:

    To do: Two two-digit integers are entered. 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: The 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, 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
    

    Expected output:

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

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

    Lab 4. 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 entered 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 return them to the Main function.

    Note 1: The method returns no value (which is why you have to use void in a 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.

    Expected output:

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

    [Solution and Project name: Lesson_5Lab4, file name L5Lab4.cs]

    ✍ Algorithm:

    • Create Console Application with the name Lesson_5Lab4.
    • In the Solution Explorer window find a file Program.cs and rename it into L5Lab4.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 out inside the function.
    • Now we’re going 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:
    • using static System.Console;
      using static System.Math;
    • Since now you don’t need to print Console.ReadLine() or Console.WriteLine(...), it is enough just to type ReadLine() or WriteLine(...):
    • ...
        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; }
         if (a < min && a != 0) { min = a; }
         ...
      
    • All we have to do now, this is to output the values of min and max in the Main function. Add the line after the calling of the function:
    • WriteLine($"minimum is: {min}, maximum is: {max}");
    • 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_5Lab4\) and upload the file L5Lab4.cs.

    Task 7:

    To do: Create PosNegSeq() method that takes two integer arguments by reference, they are counters for positive and negative values of the entered 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 entered 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;
    ...

      
      
    Expected output:

    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
    

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

    Task 8. Out arguments

    To do: Create a MaxMinSeq() method with two integer arguments, they are needed to store the minimum and maximum values of the entered 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 return them to the Main function.

    Note 1: Use out parameters by reference to return two values from a function. You don’t need to inisialize the parameteres before calling the function:

    int max, min;
    MaxMinSeq(out max, out min);

    Note 2: Since we use out parameters, which are not needed to be initialized before the calling the function, so they must be initialized within the fucntion.

    Expected output:

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

    [Solution and Project name: Lesson_5Task8, file name L5Task8.cs]

    Lab 5. Public and private access modifiers

    To do: Create a new project. Add a new class-file to the project. Create a method within this class to calculate the product of all integers divisible by 3 from A to B inclusive. Call the method from within the Main function.

    Expected output:

    Enter two integers:
    3
    9
    The result is 162
    

    [Solution and Project name: Lesson_5Lab5, file name L5Lab5.cs]

    ✍ Algorithm:

    • Create Console Application with the name Lesson_5Lab4.
    • In the Solution Explorer window find a file Program.cs and rename it into L5Lab5.cs.
    • Within the Main function ask user to enter two integers. Also declare two variables (a and b) to store entered values — upper and lower bounds of sequnse:
    • Console.WriteLine("Enter two integers:");
      int a = Int32.Parse(Console.ReadLine());
      int b = Int32.Parse(Console.ReadLine());
    • Now we’re going to create a function to solve the problem of the task. The code of the function will be in new created file with a name class1.cs. Create a file in the Solution Explorer window: right click on the project nameAddClass.
    • As a result, in the Solution Explorer window you’ll see the name Class.cs. Open the file’s code.
    • Within the class curly braces type the following function signature:
    • public static double Product(int a, int b) 
              {
       
              }

      To make the code of the function accessible from the outside of the current class, the public modifier is needed.
      To call the function from within the static Main function, static keyword is needed.
      We use int keyword since the function returns an integer.

    • Within the function initialize the variable to store the product:
    • int p = 1;
    • Create a for loop to iterate over the numbers from a to b bounds. Check to see if the number is divisible by 3:
    • for (int i = a; i <= b; i++)
                  {
                      if (i % 3 == 0)
                      {
                          p *= i;
                      }
                  }
    • Return the calculated result after the loop body:
    • return p;
    • After, open code of the Main function and add the calling of the created function:
    • //...
      Console.WriteLine($"The result is {Class1.Product(a, b)}");
      To get an access to the function from another class-file, we need to use the name of the class, i.e. Class1.
    • Run the application and debug it.

    Task 9

    To do: Create a new project. Add a new class-file to the project. Create a method within this class to calculate the following sequence: 1 + A + A2 + A3 + … + AN. A must be entered double number. N is entered integer greater than 0. You shouldn’t use a standard pow() method; to calculate the power of the numbers you should use loop.

    Expected output:

    Enter A: 1,5
    Enter N: 6
    The sequence sum is: 32,171875
    

    [Solution and Project name: Lesson_5Task9, file name L5Task9.cs]

    Windows Forms Applications

    Lab 6

    To do: Create a project to calculate a factorial of a number. The calculation must be performed as a user-defined function. The function should be run by clicking on the Calculate (btnCalc) button. The result should be displayed in a text box (txtFactorial).

    [Solution and Project name: Lesson_5Lab6, file name L5Lab6.cs]

    ✍ Algorithm:

    1. Create a new project and design the interface of the new form yourself.
    2. You need to create a user function. Double click on the button. In the window that opens, add the code before the code for the button:
    3. private long Factorial(int n)
              {
                  //...
              }
      As we can see from the signature of the function, its argument will be an integer (n), and the return value will be of type Long.
    4. The following code must be placed in the body of the function:
    5. long p = 2;
      for (int i = 3; i <= n; i++)
         p = p * i;
      return p;
    6. Now, to calculate the value of the factorial when you click the Calculate button, you need to program the Click event of the button as follows:
    7. int numb;
      if (int.TryParse(txtN.Text, out numb))
                  {
                      txtFactorial.Text = Class1.Factorial(numb).ToString();
                  }
      else
                      MessageBox.Show("введите число");
      The TryParse() method is used to validate the entered value. If a number is entered, then the result of the conversion to an integer will be stored in the numb variable. If an invalid value is entered, a message is displayed.
    8. Run and debug the application.
    9. Since our function is described using the private modifire, it will be available only from the class of this form. In order to make it available to any class of our application, you need to describe it in a class, changing private to public.
    10. Using the Solution explorer window (right click button on the project’s name) add Class, add a standard class to your project. Change the private keyword to public and add static.
    11. class Class1
          {
              public static long Factorial(int n)
              {
                  long p = 2;
                  for (int i = 3; i <= n; i++)
                      p = p * i;
                  return p;
              }
          }
    12. In the code for the button, change the Function function call to Class1.Factorial(numb).ToString().
    13. Run and debug the program.
    Extra Task for lab 6:

    Add a function to calculate the power of a number: xn, n is a natural number. Change the appearance of the form.

    Extra tasks

    Extra Task 1:

    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).
      
    Expected output:

    Please enter a number:
    15,625
    The result is 2.5 : 15.625 ^ 1/3
    

      
    [Solution and Project name: Lesson_5ExTask1, file name L5ExTask1.cs]

    Extra Task 2:

    To do: A real number A and an integer N (≥ 0) are entered. 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 2: Do not use standard pow function for the degree, accumulate the values of degrees using a loop.

    Expected output:

    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
    

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

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

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

    *
    *


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