Type Here to Get Search Results !

Program to compute the sum of two complex numbers.

C Program to compute the sum of two complex numbers
Program to compute the sum of two complex numbers.

#include <stdio.h>
typedef struct complex
{
float real;
float imag;
}complex;
complex add(complex nl, complex n2);
int main()
{
complex nl,n2,temp; // Declaring variables of type 'complex'
// Reading values into members of the 'complex' type variables
printf("For 1st complex number \n");
printf("Enter real and imaginary respectively:\n");
scanf("%f%f",&n1.real,&n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter real and imaginary respectively:\n");
scanf("%r/of", &n2.real, &n2.imag);
// Calling the add functions with two 'complex' type parameters
temp = add(n1,n2);
printf("Sum=%.1f + %.1fi", temp.real, temp.imag);
return 0;
}
/* Defining add function */
complex add(complex n1,complex n2
{
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return(temp);
}







We can pass variables of a structure type to functions and return a structure type too












n1,n2àn1 and n2, two 'complex' type parameters are passed to 'add'
temp à'add' returns a 'complex' type value

'add' function takes two 'complex' type parameters and returns 'complex' type
Output:
For 1st complex number
Enter real and imaginary respectively:
12.25
25

For 2nd complex number
Enter real and imaginary respectively:
12.25
25
Sum = 24.5 + 50.0

#include <stdio.h>

struct Complex {
    float real;
    float imag;
};

struct Complex addComplex(struct Complex c1, struct Complex c2) {
    struct Complex c3;
    c3.real = c1.real + c2.real;
    c3.imag = c1.imag + c2.imag;
    return c3;
}

int main() {
    struct Complex c1, c2, c3;
    printf("Enter the first complex number (real and imaginary parts): ");
    scanf("%f %f", &c1.real, &c1.imag);
    printf("Enter the second complex number (real and imaginary parts): ");
    scanf("%f %f", &c2.real, &c2.imag);
    c3 = addComplex(c1, c2);
    printf("Sum of the two complex numbers: %.2f + %.2f", c3.real, c3.imag);
    return 0;
}

This program uses a struct called 'Complex' to represent complex numbers, with 'real' and 'imag' members to store the real and imaginary parts of the complex number, respectively. The 'addComplex' function takes in two 'Complex' structs and returns the sum of the two complex numbers, which is also a 'Complex' struct. In the 'main' function, the program prompts the user to enter two complex numbers, calls the 'addComplex' function to compute their sum, and then prints the result.

OUTPUT:
Enter the first complex number (real and imaginary parts): 
13.26
26
Enter the second complex number (real and imaginary parts): 
18.74
24
Sum of the two complex numbers: 32.00 + 50.00

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad