Struct with Function in C

Level 4201 keystrokes

Passes struct by value to a function that calculates dot product of vectors.

C code

// Define 2D vector structure using typedef
1typedef struct {
2 float x, y;
3} Vector2;
4
// The function receives copies of both vectors (pass by value)
5float dot(Vector2 a, Vector2 b) {
// Dot product: x1*x2 + y1*y2
6 return a.x * b.x + a.y * b.y;
7}
8
// Create first vector (3, 4)
9Vector2 v1 = {3.0, 4.0};
// Create second vector (2, 1)
10Vector2 v2 = {2.0, 1.0};
// 3*2 + 4*1 = 10; %.1f prints 10.0
11printf("Dot product: %.1f\n", dot(v1, v2));

Output

Dot product: 10.0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • .× 9
  • ,× 6
  • ;× 6
  • {× 4
  • }× 4
  • (× 3
  • )× 3
  • "× 2
  • *× 2
  • =× 2

More C examples at level 4

← C typing practice