Access Middle Digit Number in Java

Write a program in Java to accept a positive integer from the user. If the number has odd number of digits, then display the square of the middle digit. But if the number has even number of digits, then display the square root of the sum of the square of the two digits in the middle.

Example 1:
INPUT:
N = 12345
OUTPUT:
Middle number = 3.
Square of the middle number = 9.

Example 2:
INPUT:
N = 123456
OUTPUT:
Middle number = 34
Sum of the squares of digits = 32 + 42 = 25.
Square root = 5.0

import java.io.*;
class Middle{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int num = Math.abs(Integer.parseInt(br.readLine()));
        int count = 0;
        for(int i = num; i != 0; i /= 10)
            count++;
        if(count % 2 == 1){
            for(int i = 1; i <= count / 2; i++){
                num /= 10;
            }
            int mid = num % 10;
            System.out.println("Middle number = " + mid);
            System.out.println("Square of the middle number = " + mid * mid);
        }
        else{
            for(int i = 1; i < count / 2; i++){
                num /= 10;
            }
            int mid = num % 100;
            System.out.println("Middle number = " + mid);
            int first = mid / 10;
            int second = mid % 10;
            int sum = first * first + second * second;
            System.out.println("Sum of the square of digits = " + sum);
            double s = Math.sqrt(sum);
            System.out.println("Square root = " + s);
        }
    }
}

3 thoughts on “Access Middle Digit Number in Java”

  1. Sir,a program is given which states that:
    Permutation and combination of 2 numbers n and r are calculated as:
    nPr=!n/!(n-r)
    nCr=!n/(!(n-r)*!r)
    where permutation is denoted as nPr and combination is denoted as nCr.The nPr means permutation of n and r & nCr means combination of n and r.
    WAP in java to accept 2 nos n and r by using the above formula.
    Sample Input:
    N=11
    R=10
    Sample Output:
    nPr is:39916800
    nCr is:11
    Display an appropriate message if n or r is less than 0

Leave a Reply

%d bloggers like this: