BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C Program to Add Two Complex Numbers

By Chaitanya Singh | Filed Under: C Programs

In this tutorial, you will learn how to write a C program to add two complex numbers. A complex number has two parts: real and imaginary. For example, in a complex number 10 + 15i the real part is 10 and the imaginary part is 15.

When two complex numbers are added, the real and imaginary parts of first number is added to the real and imaginary parts of second number respectively. For example, adding 10 + 20i with another complex number 20 + 30i would produce the result: 30 + 50i.

Program to add two complex numbers

#include <stdio.h>
//defining structure for complex number
typedef struct complex {
  float real;
  float imag;
} complex;

complex add(complex num1, complex num2);

int main() {
  complex num1, num2, sum;
  //Get real and imaginary parts of first complex number
  printf("Enter the real part of the first complex number: ");
  scanf("%f", &num1.real);
  printf("Enter the imaginary part of the first complex number: ");
  scanf("%f", &num1.imag);
  printf("First complex number: %.1f + %.1fi", num1.real, num1.imag);

  //Get real and imaginary parts of second complex number
  printf("\n\nEnter the real part of the second complex number: ");
  scanf("%f", &num2.real);
  printf("Enter the imaginary part of the second complex number: ");
  scanf("%f", &num2.imag);
  printf("Second complex number: %.1f + %.1fi", num2.real, num2.imag);

  sum = add(num1, num2);

  printf("\n\nSum of input numbers: %.1f + %.1fi", sum.real, sum.imag);
  return 0;
}

complex add(complex num1, complex num2) {
  complex temp;
  temp.real = num1.real + num2.real;
  temp.imag = num1.imag + num2.imag;
  return (temp);
}

Output:

Enter the real part of the first complex number: 10
Enter the imaginary part of the first complex number: 15
First complex number: 10.0 + 15.0i

Enter the real part of the second complex number: 15
Enter the imaginary part of the second complex number: 15
Second complex number: 15.0 + 15.0i

Sum of input numbers: 25.0 + 30.0i

Related C Examples:

  • C Program to print Pyramid star pattern
  • C Program to count number of digits in an integer
  • C Program to generate multiplication table
  • C Program to print string using pointer
❮ C TutorialC Programs ❯

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap