Vector Operations


/ Published in: C
Save to your folder(s)

Output:

Vector A:
x: 1.000000
y: 2.000000
z: 3.000000

Vector B:
x: 2.000000
y: 3.000000
z: 4.000000

Adding A and B gives the vector:
x: 3.000000
y: 5.000000
z: 7.000000

Dot product of A and B is 20.000000.

Cross product of A and B gives the vector:
x: -1.000000
y: 2.000000
z: -1.000000

Multiplying A by the scalar quantity 5.0 gives the vector:
x: 5.000000
y: 10.000000
z: 15.000000


Copy this code and paste it in your HTML
  1. #include <stdio.h>
  2.  
  3. struct vector {
  4. float x;
  5. float y;
  6. float z;
  7. };
  8.  
  9. void printVec(struct vector vec){
  10. printf("x: %f\ny: %f\nz: %f\n\n", vec.x, vec.y, vec.z);
  11. }
  12.  
  13. void addVec(struct vector op1, struct vector op2, struct vector *result){
  14. result->x = op1.x + op2.x;
  15. result->y = op1.y + op2.y;
  16. result->z = op1.z + op2.z;
  17. }
  18.  
  19. void initVec(float x, float y, float z, struct vector *vec){
  20. vec->x = x; vec->y = y; vec->z = z;
  21. }
  22.  
  23. void multVec(float scalar, struct vector *vec){
  24. vec->x *= scalar; vec->y *= scalar; vec->z *= scalar;
  25. }
  26.  
  27. float dotVec(struct vector A, struct vector B){
  28. return ((A.x * B.x) + (A.y * B.y) + (A.z * B.z));
  29. }
  30.  
  31. void crossVec(struct vector A, struct vector B, struct vector *C){
  32. C->x = ((A.y * B.z) - (A.z * B.y));
  33. C->y = ((A.z * B.x) - (A.x * B.z));
  34. C->z = ((A.x * B.y) - (A.y * B.x));
  35. }
  36.  
  37. void main(){
  38. struct vector A;
  39. struct vector B;
  40. struct vector C;
  41. initVec(1.0, 2.0, 3.0, &A);
  42. initVec(2.0, 3.0, 4.0, &B);
  43. printf("Vector A:\n");
  44. printVec(A);
  45. printf("Vector B:\n");
  46. printVec(B);
  47. printf("Adding A and B gives the vector:\n");
  48. addVec(A, B, &C);
  49. printVec(C);
  50. printf("Dot product of A and B is %f.\n\n", dotVec(A, B));
  51. printf("Cross product of A and B gives the vector:\n");
  52. crossVec(A, B, &C);
  53. printVec(C);
  54. printf("Multiplying A by the scalar quantity 5.0 gives the vector:\n");
  55. multVec(5.0, &A);
  56. printVec(A);
  57. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.