C Program to Add Two Complex Number Using User Defined Function
In this C programming example we present two different approach to add two complex number using user defined function. First, we use structure and user defined function. Second, we use structure, typedef and user defined function.
Using Structure & User Defined Function
Following C program adds two complex number using structure and user defined function.
C Source Code
#include<stdio.h>
/* Declaring Structure */
struct complex
{
float real;
float imaginary;
};
/* Function prototype */
struct complex add(struct complex a, struct complex b);
/* Main function */
int main()
{
/* Declaring structure variable using complex */
struct complex cnum1, cnum2, sum;
printf("Enter real and imaginary part of first complex number:\n");
scanf("%f%f", &cnum1.real, &cnum1.imaginary);
printf("Enter real and imaginary part of second complex number:\n");
scanf("%f%f", &cnum2.real, &cnum2.imaginary);
sum = add(cnum1, cnum2);
printf("SUM = %0.2f + i %0.2f", sum.real, sum.imaginary);
return 0;
}
/* Function definition */
struct complex add(struct complex a, struct complex b)
{
struct complex s;
s.real = a.real + b.real;
s.imaginary = a.imaginary + b.imaginary;
return s;
}
Output
Enter real and imaginary part of first complex number: 1 2 Enter real and imaginary part of second complex number: 2 3 SUM = 3.00 + i 5.00
Using Structure, Typedef & User Defined Function
Following C program adds two complex number using structure, typedef and user defined function.
C Source Code
#include<stdio.h>
/* Declaring Structure */
typedef struct
{
float real;
float imaginary;
}complex;
/* Function prototype */
complex add(complex a, complex b);
/* Main function */
int main()
{
/* Declaring structure variable using complex */
complex cnum1, cnum2, sum;
printf("Enter real and imaginary part of first complex number:\n");
scanf("%f%f", &cnum1.real, &cnum1.imaginary);
printf("Enter real and imaginary part of second complex number:\n");
scanf("%f%f", &cnum2.real, &cnum2.imaginary);
sum = add(cnum1, cnum2);
printf("SUM = %0.2f + i %0.2f", sum.real, sum.imaginary);
return 0;
}
Output
Enter real and imaginary part of first complex number: 3 8 Enter real and imaginary part of second complex number: 2 6 SUM = 5.00 + i 14.00