Write a program that defines a:

  • $\texttt{complex}$ type
  • function that calculates the module of a complex number
  • function that calculates the conjugate of a complex number
  • function that prints a complex number
  • function that calculates the sum of 2 complex numbers

Write a main function to test your functions.


Difficulty level
This exercise is mostly suitable for students
#include <math.h>
#include <stdio.h>

typedef struct {
  double re;
  double im;
} complex;

double module(complex c)
{
	return sqrt(c.re*c.re+c.im+c.im);
}

complex conjug(complex c)
{
	complex r;
	r.re = c.re;
	r.im = -c.im;
	return r;
}

complex add_complex(complex c1, complex c2)
{
	complex r;
	r.re = c1.re + c2.re;
	r.im = c1.im + c2.im;
	return r;
}

void print_complex(complex c)
{
	printf("%.1f + %.1fi\n", c.re, c.im);
}

void main() 
{ 
  complex z = {1.0, 2.0 }, one = {1.0, 0.0 }, i = { 0.0, 1.0 }, r;
  print_complex(conjug(z));
  print_complex(add_complex(one,i));
  printf("%.2f\n", module(z));
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
2 players Game - version 1