C Program to find hypotenuse without math.h

Write a C program to find hypotenuse of a right-angled triangle without using math.h.

Let P be the perpendicular and B be the base of a right-angled triangle. The hypotenuse, H is given by

H = \sqrt{P^2 + B^2}

We can easily find the hypotenuse using the above formula but the catch is we cannot use math.h. Therefore, we cannot use sqrt() to calculate the square root.

We will implement our own sqrt() function. We can do it using Newton’s method or Binary Search (both methods are very similar). In this post, we will use binary search to find the square root of a number.

Program

#include<stdio.h>
#include<string.h>

// function to calculate square root of n
// using binary search
double sqrt(double n){
	
	double start,end,mid;
	// the square root of n must lie between 0 and n
	start = 0, end = n;
	// in each iteration, we compare mid with n
	// and modify start and end such that they converge
	// closer and closer to square root of n
	while((end - start)>=0.000001){
		mid = (start + end)/2;	
		if(mid*mid < n)
			start = mid;
		if(mid*mid >= n)
			end = mid;
	}
	return mid;
	
}

int main() {
	
	double H,B,P;
	printf("Enter Base of the Triangle: ");
	scanf("%lf", &B);
	printf("Enter Height/Perpendicular of the Triangle: ");
	scanf("%lf", &P);
	H = sqrt(B*B + P*P);
	printf("Hypotenuse of Triangle: %lf", H);
	
}

Output

hypotenuse without sqrt() and pow()

Leave a Comment

Your email address will not be published. Required fields are marked *