c
  1. c-program-to-add-two-complex-numbers-by-passing-structure-to-a-function

Program to Add Two Complex Numbers by Passing Structure to a Function - (C Programs)

In this tutorial, we'll cover a C program that adds two complex numbers by passing a structure to a function. This program uses structures in C to define complex numbers and passes them as arguments to a function that performs the addition operation.

Syntax

The syntax for defining a structure to represent a complex number in C is as follows:

typedef struct complex {
    float real;
    float imag;
} complex;

The syntax for declaring a function that adds two complex numbers in C is as follows:

complex add(complex num1, complex num2);

Example

#include <stdio.h>

typedef struct complex {
    float real;
    float imag;
} complex;

complex add(complex num1, complex num2) {
    complex result;
    result.real = num1.real + num2.real;
    result.imag = num1.imag + num2.imag;
    return result;
}

int main() {
    complex num1, num2, result;

    printf("Enter the real and imaginary parts of the first complex number:\n");
    scanf("%f %f", &num1.real, &num1.imag);

    printf("Enter the real and imaginary parts of the second complex number:\n");
    scanf("%f %f", &num2.real, &num2.imag);

    result = add(num1, num2);

    printf("The sum of the two complex numbers is: %.2f + %.2fi\n", result.real, result.imag);

    return 0;
}

Output

Enter the real and imaginary parts of the first complex number:
3.2 2.1
Enter the real and imaginary parts of the second complex number:
1.3 4.2
The sum of the two complex numbers is: 4.50 + 6.30i

Explanation

The program defines a structure complex that holds the real and imaginary parts of a complex number. A function add is defined that takes two complex numbers as input and returns their sum as a complex number.

In the main function, two complex numbers are read in from the user, and the add function is called to compute their sum. Finally, the program prints the sum of the two complex numbers.

Use

This program demonstrates how to define structures in C to represent complex numbers and how to pass these structures as arguments to a function. Also, this program shows how to manipulate and perform arithmetic operations on complex numbers.

Summary

In this tutorial, we discussed a C program that adds two complex numbers by passing a structure to a function. The program defines a complex structure to represent complex numbers, along with a function add that adds two complex numbers. Finally, the program takes in two complex numbers as inputs from the user, passes them to the add function, and displays the result.

Published on: