C PROGRAMMING PROGRAM • STRUCTURES, UNIONS & ENUMS
Add Two Complex Numbers Using Structures
Learn how to add two complex numbers using structures using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
3 4 5 -2
Sample output
Sum = 8.00 + 2.00i
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
struct Complex
{
double real;
double imaginary;
};
struct Complex add(struct Complex first, struct Complex second)
{
struct Complex result = {first.real + second.real, first.imaginary + second.imaginary};
return result;
}
int main(void)
{
struct Complex first, second, result;
printf("Enter real and imaginary parts of first number: ");
scanf("%lf %lf", &first.real, &first.imaginary);
printf("Enter real and imaginary parts of second number: ");
scanf("%lf %lf", &second.real, &second.imaginary);
result = add(first, second);
printf("Sum = %.2f %c %.2fi\n", result.real,
result.imaginary < 0 ? '-' : '+', result.imaginary < 0 ? -result.imaginary : result.imaginary);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sum = 8.00 + 2.00i
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Add corresponding real and imaginary members and return the result structure.
- Display the computed result.
Add corresponding real and imaginary members and return the result structure.
EFFICIENCY
Time and space complexity
Time complexity
O(1)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
