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 statistics1typedef struct {2 int min, max, sum;3} Stats;4 // Function returns a Stats struct5Stats getStats(int arr[], int n) { // min and max start at the first element, sum starts at 06 Stats s = {arr[0], arr[0], 0};7 for (int i = 0; i < n; i++) { // Update minimum if smaller8 if (arr[i] < s.min) s.min = arr[i]; // Update maximum if larger9 if (arr[i] > s.max) s.max = arr[i]; // Add to sum10 s.sum += arr[i];11 } // Return entire struct12 return s;13}14 15int nums[] = {5, 2, 8, 1, 9};// The whole struct is copied into result16Stats result = getStats(nums, 5);// Prints Min: 1, Max: 9, Sum: 2517printf("Min: %d, Max: %d, Sum: %d\n", result.min, result.max, result.sum);Output
Min: 1, Max: 9, Sum: 25
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