w3resource

Java Exercises: Compute the square root of a given integer

Java Basic: Exercise-117 with Solution

Write a Java program to compute the square root of a given integer.

Pictorial Presentation:

Java Basic Exercises: Compute the square root of a given integer

Sample Solution:

Java Code:

import java.util.*; 
public class Exercise117 {
 public static void main(String[] args)
 {
        int num;
        Scanner in = new Scanner(System.in);	
        System.out.print("Input a positive integer: ");
        int n = in.nextInt(); 
        System.out.printf("Square root of %d is: ",n);
		System.out.println(sqrt(n)); 
    }
    
private static int sqrt(int num) {
        if (num == 0 || num == 1) {
			return num;
		}
		int a = 0;
		int b = num;
		while (a <= b) {
			int mid = (a + b) >> 1;
			if (num / mid < mid) {
				b = mid - 1;
			} else {
				if (num / (mid + 1) <= mid) {
					return mid;
				}
				a = mid + 1;
			}
		}
		return a;
	}
}

Sample Output:

Input a positive integer: 25                                           
Square root of 25 is: 5 

Flowchart:

Flowchart: Java exercises: Compute the square root of a given integer

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program which iterates the integers from 1 to 100. For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". When number is divided by both three and five, print "fizz buzz".
Next: Write a Java program to get the first occurrence (Position starts from 0.) of a string within a given string.

What is the difficulty level of this exercise?



Java: Tips of the Day

initial:

Returns all the elements of an array except the last one. Use Arrays.copyOfRange() to return all except the last one

public static <T> T[] initial(T[] elements) {
    return Arrays.copyOfRange(elements, 0, elements.length - 1);
}

Ref: https://bit.ly/3zEKw9u