# C++ real() function with examples

In this article, we will be learning C++ – real() function with examples. The real() function in C++ is defined header file “complex.h”. It comes handy when we need to find the real part of a complex number. It takes a parameter that holds the complex number and returns the real part of the complex number.

At first, let us see how a complex number looks like. A complex number has two parts – the real part and the imaginary part. The imaginary part is preceded by *‘i’ *and has a form of a+ib where a is the real part and b is the imaginary part. Few examples are:-

- 5 + 7i
- 0 + 5i

**Syntax:-** template< class T >

constexpr T real( const std::complex<T>& z );

here z is the parameter which holds the complex number.

## real() function and examples

- In the below program, we will find the real part of the complex number 7 + 9i with the real() function.
#include <bits/stdc++.h> using namespace std; int main() { complex<double> comp(7, 9); //declaring comp with 7+9i cout << "Complex number with imaginary part: " << comp << endl; //prints the complete complex number cout << "Real part: " << real(comp) << endl; //prints the real part of the complex number return 0; }

The code generates the following output:-

Complex number with imaginary part: (7,9) Real part: 7 -------------------------------- Process exited after 0.05535 seconds with return value 0 Press any key to continue . . .

- In the below program, we will find the real part of the complex number 0+i with real() function.
#include <bits/stdc++.h> using namespace std; int main() { complex<double> comp( 0, 1); //declaring comp with 0+i cout << "Complex number with imaginary part: " << comp << endl; //prints the complete complex number cout << "Real part: " << real(comp) << endl; //prints the real part of the complex number return 0; }

The code generates the following output:-

Complex number with imaginary part: (0,1) Real part: 0 -------------------------------- Process exited after 0.06017 seconds with return value 0 Press any key to continue . . .

I hope you understood what we see in this article.

## Leave a Reply

You must be logged in to post a comment.