IQ

Ad SpeedyAds

Wednesday, February 8, 2012

java program: Recursive function to multiply two numbers

// to multiply 2 nos. using recursive functions
import java.io.*;
class recursiveMultiplication
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a number: ");
String s=br.readLine();
System.out.print("Enter another number: ");
String S=br.readLine();
int a=Integer.parseInt(s);
int b=Integer.parseInt(S);
if((a<0&&b>0)||(a>0&&b<0))
System.out.print(-Mult(Math.abs(a),Math.abs(b)));
else System.out.print(Mult(Math.abs(a),Math.abs(b)));
}
public static int Mult(int a, int b)
{
if(a==0||b==0)
return 0;
else if(b==1)
return a;

return(a+Mult(a,(b-1)));
}

}

No comments:

Post a Comment