What is Power Function in C Library?

Question: What is Power Function in Standard C Library?

Answer: There are two functions in this family which are defined in ‘math.h’ header and are prototyped below

    double pow(double x, double y);
    double sqrt(double value);

Power ‘pow()’ function returns x raised to power y. Since logarithms may be used to compute the exp. ‘x^y’, x can’t be negative and y can’t be non-integer. If, this is so, domain error occurs!

/* fp_pow_fun.c -- pow() function computes exp. of forms 'x^y' */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
int main(void)
{
    double x, y, result;
 
    printf("User, enter +ve value for 'x' and Integral Value for 'y' "
            "to evaluate \"x^y\"...\n");
    printf("Power \"x^y\" with -ve 'x' and Non-Integral 'y' "
             "causes DOMAIN ERROR!\n");
    scanf("%lf %lf", &x, &y);
 
    /* pow() function executes */
    result = pow(x, y);
 
    /* Display the result */
    printf("Pow \"%lf^%lf\" : %lf\n", x, y, result);
 
    return 0;
}

Example of Square-Root ‘sqrt()’ function:

advertisement
advertisement
/* fp_sqrt_fun.c -- sqrt() function computes square-root of +ve values */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
int main(void)
{
    double sqrt_of, result;
 
    printf("User, enter +ve value of which you seek Square-Root of...\n");
    printf("Square-Root of Negative Values causes DOMAIN ERROR!\n");
    scanf("%lf", &sqrt_of);
 
    /* sqrt() function executes */
    result = sqrt(sqrt_of);
 
    /* Display the result */
    printf("Square-Root of \"%lf\": %lf\n", sqrt_of, result);
 
    return 0;
}

Output for some arbitrary values as follows:

User, enter +ve value of which you seek Square-Root of...
Square-Root of Negative Values causes DOMAIN ERROR!
5
Square-Root of "5.000000": 2.236068
 
User, enter +ve value of which you seek Square-Root of...
Square-Root of Negative Values causes DOMAIN ERROR!
-10
Square-Root of "-10.000000": -nan

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.