Programming Course in C# ¡Free!

Function Multiply & MultiplyR

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create two functions, Multiply and MultiplyR, to calculate the product of two numbers using sums. The first version must be iterative, and the second one must be recursive.

Output



Solution


using System;
public class Multiply
{
public static int Mul( int n1, int n2)
{
if (n2 == 0)
return 0;
else
return n1 + Mul( n1, n2 - 1 );
}   

public static int Main( )
{
if (args.Length != 2)
{
Console.WriteLine("Error arguments!!");
return 1;
}

int n1 = Convert.ToInt32( args[0] );       
int n2 = Convert.ToInt32( args[1] );       

Console.WriteLine( Mul( n1, n2 ) );
return 0;  
}
}