C Program to add two complex numbers by using Structure
Objective
Write a C program to add two complex numbers by passing structures to a function.
Algorithm / Approach
- Define a structure
complexwith floatsr(real) andi(imaginary). - Use
typedefto aliasstruct complexto justcomplex. - Create a function prototype
complex add(complex n1, complex n2). - Read the two complex numbers in
main()and pass them toadd(). - Inside
add(), create a temporary structure, add the real parts, add the imaginary parts, and return the temporary structure.
main.c
#include<stdio.h>
typedef struct complex{
float r;
float i;
}complex;
complex add(complex n1,complex n2);
int main( ) {
complex n1,n2,t;
printf("For 1st complex no. : \n");
printf("Enter real & imag. part:");
scanf("%f%f",&n1.r,&n1.i);
printf("For 2nd complex no. : ");
printf("Enter real & imag. part:");
scanf("%f%f",&n2.r,&n2.i);
t=add(n1,n2);
printf("Sum=%.1f+%.1fi",t.r,t.i);
return 0;
}
complex add(complex n1,complex n2) {
complex temp;
temp.r=n1.r+n2.r;
temp.i=n1.i+n2.i;
return(temp);
}
Expected Output
For 1st complex number : Enter real & imaginary respectively : 3 4.5 For 2nd complex number : Enter real & imaginary respectively : 3.2 5 Sum = 6.2 + 9.5i
Explanation of the Program
- Complex numbers have two distinct parts (real and imaginary), making them a perfect candidate for a structure.
- This program shows that structures can be passed into functions as arguments, and functions can even return an entire structure as their return type! The
typedefkeyword makes the code cleaner so we don't have to typestructevery time.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)