- 2068 Shrawan · 10 marks
Complex number sum via functions
Write a program to represent complex number by a structure with real and imaginary as members. Take 2 complex numbers as input from user into structure variables. Pass the complex numbers to a function which calculates sum and returns it. Display the sum from another function display().
Design.
- The structure
complexhasrealandimagmembers. main()reads two complex numbers into the structure variablesc1andc2.add()takes the two structures (by value), adds the real and imaginary parts separately, and returns the sum as a structure.display()receives the sum and prints it in the form a + bi.
#include <stdio.h>
struct complex {
float real;
float imag;
};
struct complex add(struct complex a, struct complex b)
{
struct complex s;
s.real = a.real + b.real;
s.imag = a.imag + b.imag;
return s;
}
void display(struct complex c)
{
printf("Sum = %.1f %c %.1fi\n", c.real, c.imag < 0 ? '-' : '+',
c.imag < 0 ? -c.imag : c.imag);
}
int main(void)
{
struct complex c1, c2, sum;
printf("Enter first complex number (real imaginary): ");
scanf("%f %f", &c1.real, &c1.imag);
printf("Enter second complex number (real imaginary): ");
scanf("%f %f", &c2.real, &c2.imag);
sum = add(c1, c2);
display(sum);
return 0;
}
Sample run (3 + 4i and 1.5 − 6i)
Input: 3 4 1.5 -6
Enter first complex number (real imaginary): Enter second complex number (real imaginary): Sum = 4.5 - 2.0i
(3 + 1.5) + (4 − 6)i = 4.5 − 2i.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Function definition; sum of two numbers · Computer Programming, chapter 6
- Complex number multiplication using structure · Computer Programming, chapter 8
- Sending structure members to a function · Computer Programming, chapter 8
- Insert a string into another string · Computer Programming, chapter 7
- Pass student array; display passed students · Computer Programming, chapter 7
- GOTO types; sum of series program · Computer Programming, chapter 11
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9
- LandMeasure class and sum function · Object Oriented Programming, chapter 4
- Complex numbers relational operators · Object Oriented Programming, chapter 5
- 8086 ALP: sum of 100 even numbers · Microprocessor, chapter 3