Return Struct in C

Level 4384 keystrokes

Returns a struct from a function to return multiple computed values at once.

C code

// Define struct to hold multiple statistics
1typedef struct {
2 int min, max, sum;
3} Stats;
4
// Function returns a Stats struct
5Stats getStats(int arr[], int n) {
// min and max start at the first element, sum starts at 0
6 Stats s = {arr[0], arr[0], 0};
7 for (int i = 0; i < n; i++) {
// Update minimum if smaller
8 if (arr[i] < s.min) s.min = arr[i];
// Update maximum if larger
9 if (arr[i] > s.max) s.max = arr[i];
// Add to sum
10 s.sum += arr[i];
11 }
// Return entire struct
12 return s;
13}
14
15int nums[] = {5, 2, 8, 1, 9};
// The whole struct is copied into result
16Stats result = getStats(nums, 5);
// Prints Min: 1, Max: 9, Sum: 25
17printf("Min: %d, Max: %d, Sum: %d\n", result.min, result.max, result.sum);

Output

Min: 1, Max: 9, Sum: 25
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.

  • ,× 15
  • ;× 12
  • [× 9
  • ]× 9
  • .× 8
  • =× 7
  • (× 6
  • )× 6
  • {× 5
  • }× 5

More C examples at level 4

← C typing practice