Computer Science, asked by qwer638ry5tyuiop, 4 months ago

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 anindyaadhikari13
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.

  1. import java.util.*;
  2. public class JavaBrainly {
  3. public static void main(String[] args) {
  4. Scanner sc=new Scanner(System.in);
  5. System.out.print("Enter a number: ");
  6. int n=sc.nextInt();
  7. int x=numberOfDigits(n);
  8. if(x%2==1)
  9. {
  10. x/=2;
  11. n=n/(int)(Math.pow(10, x));
  12. n=n%10;
  13. System.out.println("Middle digit: "+n);
  14. }
  15. else
  16. {
  17. System.out.println("Number has even number of digits.");
  18. }
  19. sc.close();
  20. }
  21. static int numberOfDigits(int n)
  22. {
  23. int c=0;
  24. while(n!=0)
  25. {
  26. c++;
  27. n/=10;
  28. }
  29. return c;
  30. }
  31. }

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 !
anindyaadhikari13: Thank you :)
Similar questions