C Program to Add Two Complex Numbers

In this C program, we will be adding two complex numbers. A complex number consists of a real part and an imaginary part. We will take input from the user for the real and imaginary parts of both complex numbers and then add them together.

Problem Statements

Write a C program to add two complex numbers.

C Program to Add Two Complex Numbers

#include<stdio.h>

typedef struct {
    float real;
    float imaginary;
} Complex;

Complex addComplexNumbers(Complex num1, Complex num2);

int main()
{
    Complex num1, num2, sum;

    printf("Enter real and imaginary parts of first complex number:\n");
    printf("Real Part: ");
    scanf("%f", &num1.real);
    printf("Imaginary Part: ");
    scanf("%f", &num1.imaginary);

    printf("\nEnter real and imaginary parts of second complex number:\n");
    printf("Real Part: ");
    scanf("%f", &num2.real);
    printf("Imaginary Part: ");
    scanf("%f", &num2.imaginary);

    sum = addComplexNumbers(num1, num2);

    printf("\nSum = %.2f + %.2fi", sum.real, sum.imaginary);

    return 0;
}

Complex addComplexNumbers(Complex num1, Complex num2)
{
    Complex sum;
    sum.real = num1.real + num2.real;
    sum.imaginary = num1.imaginary + num2.imaginary;
    return sum;
}

How it works

  1. We start by including the necessary header file stdio.h, which allows us to use functions like printf and scanf.
  2. We define a structure called Complex that represents a complex number. It contains two float variables: real for the real part and imaginary for the imaginary part.
  3. We declare a function addComplexNumbers that takes two complex numbers as parameters and returns the sum of the two numbers.
  4. In the main function, we declare three variables: num1 and num2 to store the two complex numbers entered by the user, and sum to store the sum of the complex numbers.
  5. We prompt the user to enter the real and imaginary parts of the first complex number, and we read the values using scanf.
  6. Similarly, we prompt the user to enter the real and imaginary parts of the second complex number, and we read the values using scanf.
  7. We call the addComplexNumbers function, passing num1 and num2 as arguments, and assign the returned value to the sum variable.
  8. Finally, we display the sum of the two complex numbers using printf, formatting it as %.2f + %.2fi to display the real and imaginary parts with two decimal places.

Input / Output

C Program to Add Two Complex Numbers

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...