Write a program to compute the middle digit of a number entered. If the number does
not have a middle digit, it has to give the average of the two middle digits.
Answers
Required Answer:-
Question:
- Write a program to compute the middle digit of a number entered. If the number does not have a middle digit, it has to give the average of two middle digits.
Solution:
Here is the program.
import java.util.*;
public class NumberOp {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number: ");
int n=sc.nextInt();
int x=countDigits(n);
if(x%2==1) {
System.out.println("Number has odd number of digits.");
n=n/(int)(Math.pow(10,x/2));
n=n%10;
System.out.println("Middle digit is: "+n);
}
else {
System.out.println("Number has even number of digits.");
n=n/(int)(Math.pow(10,x/2-1));
n=n%100;
double av=(n%10+n/10)/2.0;
System.out.println("Average of middle two digits is: "+av);
}
sc.close();
}
static int countDigits(int n) {
int c=0;
while(n!=0) {
c++;
n/=10;
}
return c;
}
}
Explanation:
- We will ask the user to enter the number. If the number of digits of the number is even, then we will display the average of the two numbers else we will display the middle digit.
Output is attached.