Home  >  Article  >  Backend Development  >  How to find the product of 2 numbers using recursion in C#?

How to find the product of 2 numbers using recursion in C#?

WBOY
WBOYforward
2023-09-03 20:13:021198browse

如何在 C# 中使用递归求 2 个数字的乘积?

First, set the two numbers you want to multiply.

val1 = 10;
val2 = 20;

Now calculate the method to find the product.

product(val1, val2);

Under the product method, recursive calls will obtain the product.

val1 + product(val1, val2 – 1)

Let’s see the complete code to find the product of 2 numbers using recursion.

Example

using System;
class Calculation {
   public static void Main() {
      int val1, val2, res;
      // the two numbers
      val1 = 10;
      val2 = 20;
      // finding product
      Demo d = new Demo();
      res = d.product(val1, val2);
      Console.WriteLine("{0} x {1} = {2}", val1, val2, res);
      Console.ReadLine();
   }
}
class Demo {
   public int product(int val1, int val2) {
      if (val1 < val2) {
         return product(val2, val1);
      } else if (val2 != 0) {
         return (val1 + product(val1, val2 - 1));
      } else {
         return 0;
      }
   }
}

The above is the detailed content of How to find the product of 2 numbers using recursion in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete