# Vectors with Structures in C

by Dinesh Thakur Category: Structure And Union

Since structures are multivalue, multitype data objects, they can be considered to form a useful tool in manipulation of quantities such as vectors, complex variables, etc. For this we define functions of the type struct, i.e., the return value of the function is a structure. The function may have arguments of type struct besides other arguments. Let us define a structure with three components of vector as its data members as shown below.

struct vector { double x; double y; double z;};

Here, data variables x, y, and z are components of vectors. A function which adds two vectors and returns the resultant vector may be defined as below.

struct vector Vector_add(struct vector V1, struct vector V2)

{

struct vector sum;

sum.x = V1.x + V2.x;

sum.y = V1.y + V2.y; II definition of struct function

sum.z = V1.z + V2.z;

return sum;

}

Similar functions may be defined for other operations on vectors.

```#include<stdio.h>struct vector { double A[4] ; }; // structure with array as memberstruct vector Addition(struct vector V1, struct vector V2);struct vector Subtract(struct vector V1, struct vector V2);void main(){  int j,k;  struct vector V3, V4;  struct vector V1 = { 5.0, 6.0, 7.0, 8.0};  struct vector V2 = { 2.0, 2.0, 2.0, 2.0};  clrscr();  V3 =Addition( V1, V2);  V4 = Subtract(V1, V2);  printf("The components of V3 are:");  for ( j =0; j<4; j++)    printf("%.3f\t", V3.A[j]);    printf ("\n");    printf("The components of V4 are:");    for ( k =0; k<4; k++)       printf("%.2f\t", V4.A[k]);       printf ("\n");}struct vector Addition ( struct vector V1, struct vector V2){  int i;  struct vector sum;  for( i =0; i<4; i++)     sum.A[i] = V1.A[i] + V2.A[i];     return sum; }struct vector Subtract( struct vector V1, struct vector V2){  int i;  struct vector Result;  for( i =0; i<4; i++)   Result.A[i] = V1.A[i] - V2.A[i];   return Result;}
```

Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles