Write a program in java to accept a number (odd digit)and print the middle digit of that number. A number can be 3 digit, 5 digit, 7 digit etc.
Answers
Answered by
3
Required Answer:-
Question:
- Write a program in Java to accept a number and print the middle digit of that number.
Solution:
Here is the code.
- import java.util.*;
- public class JavaBrainly {
- public static void main(String[] args) {
- Scanner sc=new Scanner(System.in);
- System.out.print("Enter a number: ");
- int n=sc.nextInt();
- int x=numberOfDigits(n);
- if(x%2==1)
- {
- x/=2;
- n=n/(int)(Math.pow(10, x));
- n=n%10;
- System.out.println("Middle digit: "+n);
- }
- else
- {
- System.out.println("Number has even number of digits.");
- }
- sc.close();
- }
- static int numberOfDigits(int n)
- {
- int c=0;
- while(n!=0)
- {
- c++;
- n/=10;
- }
- return c;
- }
- }
Explanation:
- I have created a function that counts the number of digits of the number. If the number has even number of digits, then it will not display the middle digit. If the number has odd number of digits, it will display the middle digit.
- Logic to display middle digit: Count the number of digits. Divide it by two. Let it be x. Divide the number by 10^x. Using module operator, find the last digit. The last digit we got is the result.
- Example, Let the number be 123. So, number of digits is 3. Dividing by two gives 1 as quotient. 10¹ = 10. Dividing 123 by 10 gives 12 as quotient. Perform modulo operation, you will get 2 as remainder which is the middle digit.
Output is attached for verification.
Attachments:
RockingStarPratheek:
Nice !
Similar questions