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
- We start by including the necessary header file
stdio.h, which allows us to use functions likeprintfandscanf. - We define a structure called
Complexthat represents a complex number. It contains two float variables:realfor the real part andimaginaryfor the imaginary part. - We declare a function
addComplexNumbersthat takes two complex numbers as parameters and returns the sum of the two numbers. - In the
mainfunction, we declare three variables:num1andnum2to store the two complex numbers entered by the user, andsumto store the sum of the complex numbers. - We prompt the user to enter the real and imaginary parts of the first complex number, and we read the values using
scanf. - Similarly, we prompt the user to enter the real and imaginary parts of the second complex number, and we read the values using
scanf. - We call the
addComplexNumbersfunction, passingnum1andnum2as arguments, and assign the returned value to thesumvariable. - Finally, we display the sum of the two complex numbers using
printf, formatting it as%.2f + %.2fito display the real and imaginary parts with two decimal places.
Input / Output
