![The C Standard Library Reference](/c_standard_library/images/c-mini-logo.jpg)
- The C Standard Library
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Standard Library Resources
- C Library - Quick Guide
- C Library - Useful Resources
- C Library - Discussion
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C library - csqrt() function
The C complex library csqrt() function is used to calculate the sqrt (square root) of the z (complex number) with branch cut along the negative real axis.
This function is depends on the type of z(complex number). If the z is the "float" type, we can use csqrtf() to compute complex sqrt, For long double type, use csqrtl(), and for double type, use csqrt().
Syntax
Following is the C library syntax of csqrt() function −
double complex csqrt( double complex z );
Parameters
This function accepts a single parameter −
-
Z − It represent a complex number for which we want to calculate the square root.
Return Value
This function returns the square root of z. It should be in the range of the right half-plane, including the imaginary axis: [0, +∞) along the real axis and (−∞, +∞) along the imaginary axis.
Example 1
Following is the basic c program to demonstrate the use of csqrt() on a complex number.
#include <stdio.h> #include <complex.h> int main() { double complex z = 3.0 + 4.0 * I; // Compute the sqaure root of z double complex result = csqrt(z); printf("Complex square root of z: %.2f%+.2fi\n", creal(result), cimag(result)); return 0; }
Output
Following is the output −
Complex square root of z: 2.00+1.00i
Example 2
Let's see another example, calculate the square root of -ve real number using csqrt() function.
#include <stdio.h> #include <complex.h> int main(void) { double complex z1 = csqrt(-4); printf("Square root of -4 is %.1f%+.1fi\n", creal(z1), cimag(z1)); }
Output
Following is the output −
Square root of -4 is 0.0+2.0i
Example 3
The program below, defining a complex number z = 4.0i and calculating its square using the csqrt() function.
#include <stdio.h> #include <complex.h> int main() { double complex z = 4.0*I; //use csqrt() double complex res = csqrt(z); printf("csqrt(%.2f + %.2fi) = %.2f + %.2fi\n", creal(z), cimag(z), creal(res), cimag(res)); return 0; }
Output
Following is the output −
csqrt(0.00 + 4.00i) = 1.41 + 1.41i