Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to add two complex numbers by using Structure

C Code Example — Structure Programs

ADVERTISEMENT

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

  1. Define a structure complex with floats r (real) and i (imaginary).
  2. Use typedef to alias struct complex to just complex.
  3. Create a function prototype complex add(complex n1, complex n2).
  4. Read the two complex numbers in main() and pass them to add().
  5. 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 typedef keyword makes the code cleaner so we don't have to type struct every time.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT