JAVA. B03 - Multiply even digits Write a program that will ask the user for a nu
ID: 3915024 • Letter: J
Question
JAVA.
B03 - Multiply even digits Write a program that will ask the user for a number, and then recursively computes the multiplication of every even number that is less than the given number. That is, if the user enters 13, your program would recursively compute 12*10*8*6*4*2.
Hint: Define the following method:
public static long computeMultiplication(int n)
Note: Validate the user input to make sure the entered number is a positive integer. Otherwise, keep asking the user for a number until the input is valid.
Explanation / Answer
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Vamsi
*/
public class Multiplication {
public static long computeMultiplication(int n)
{
if(n==0)
return 1;
if(n%2==0)//if n is even...then multiplying
return computeMultiplication(n-1)*n;//recursive calls
return computeMultiplication(n-1);
}
public static void main(String argv[])
{
int n ;
//to read input...
Scanner sc = new Scanner(System.in);
while(true)//runs upto positive value is entered
{
System.out.println("Enter positive number :");
n = sc.nextInt();//reading number
if(n>0)//validating input
break;
}
long r = computeMultiplication(n-1);
System.out.println("Result : "+r);
}
}
output:
run:
Enter positive number :
8
Result : 48
BUILD SUCCESSFUL (total time: 2 seconds)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.