Home > Backend Development > C#.Net Tutorial > 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
Release: 2023-09-03 20:13:02
forward
1212 people have browsed it

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

First, set the two numbers you want to multiply.

val1 = 10;
val2 = 20;
Copy after login

Now calculate the method to find the product.

product(val1, val2);
Copy after login

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

val1 + product(val1, val2 – 1)
Copy after login

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;
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template