Friday, 15 April 2016

C Program To Add Two Complex Numbers By Passing Structure With Function Using Structure In C

Problem :- C Program To Add Two Complex Numbers By Passing Structure With Function Using Structure In C 

What Is Structure

Structure is a user-defined data type in C which allows you to combine different data types to store a particular type of record. Structure helps to construct a complex data type in more meaningful way. It is somewhat similar to an Array. The only difference is that array is used to store collection of similar datatypes while structure can store collection of any type of data.


Structure is used to represent a record. Suppose you want to store record of Student which consists of student name, address, roll number and age. You can define a structure to hold this information.


Defining a structure


struct keyword is used to define a structure. struct define a new data type which is a collection of different type of data.


Syntax :


struct structure_name

{
 //Statements
};

Solution :-

#include <stdio.h>

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

complex add(complex n1,complex n2);


int main()

{
    complex n1,n2,temp;
    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("%f%f",&n2.real,&n2.imag);
    temp=add(n1,n2);
    printf("Sum=%.1f+%.1fi",temp.real,temp.imag);
    return 0;
}

complex add(complex n1,complex n2)

{
      complex temp;
      temp.real=n1.real+n2.real;
      temp.imag=n1.imag+n2.imag;
      return(temp);
}

Output:-


C Program To Add Two Complex Numbers By Passing Structure With Function Using Structure In C

No comments:
Write comments

Recommended Posts × +