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); 
 }
 }
 }

No comments:

Post a Comment

any problem in any program comment:-

Second largest number in java using ternary operator

 //Largest second number using ternary operator public class Main { public static void main(String[] args) { int a=5,b=6,c=7; int ...