Read the description of finding square roots problem

finding-square-roots-problem-solution-in-c

This finding square roots problem is taken from CodeChef for practice and learning purpose only. Now, we will discuss how to solve this problem using C language. Obviously you can use other programming language but the logic can be same.

You can also implement your own logic. Let’s see the solution of this problem bellow.

Solution of this finding square roots problem

Here at the solution code we have taken an integer variable T for storing the number of test case from user. then each line will take another integer as input and determine its square root by sqrt() function which is defined under math.h header file.

Then the floor() function which is also defined inside math.h header file will make it the largest integer which is less then or equal to then number inside it.

Let’s consider,

floor(sqrt(2));

=  floor(1.41421356237);

=  1

// solution of finding square roots problem

#include <stdio.h>
#include <math.h>

int main(){
    int T, c;
    scanf("%d", &T);
    
    for(c = 1; c <= T; c++){
        double num, sqr;
        scanf("%lf", &num);
        sqr = floor(sqrt(num));
        printf("%.lf\n", sqr);
    }

return 0;
}

Now, compile and run this code then check the output for given input set. You will see the output like this.

3
10
3
5
2
10000
100

Here, first line contains 3 which is the total test case. Then we want to determine the square root of 10 which is in the second line. After pressing enter we will get the output 3 which is in the fourth line. Then another two input and their output is shown above.

This is not the only solution to this problem. You can use any other loop although we have used for loop here. So, try this using other loop which will increase your problem solving power.

Previous pageC practice

Next page:  Sum or difference