fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct
  5. {
  6. int age;
  7. float weight;
  8. } person;
  9.  
  10. /*
  11. Recursive function that:
  12. 1. Inputs data
  13. 2. Updates running totals
  14.  
  15. So we only traverse the array ONE time.
  16. */
  17. void process_people(person *p[], int i, int n, int *sum_age, float *sum_weight)
  18. {
  19. // Base case: all people processed
  20. if (i == n)
  21. return;
  22.  
  23. // Allocate memory for this person
  24. p[i] = (person*)malloc(sizeof(person));
  25.  
  26. printf("Enter age of person %d: ", i + 1);
  27. scanf("%d", &p[i]->age);
  28.  
  29. printf("Enter weight of person %d: ", i + 1);
  30. scanf("%f", &p[i]->weight);
  31.  
  32. // Update running totals
  33. *sum_age += p[i]->age;
  34. *sum_weight += p[i]->weight;
  35.  
  36. // Recursive call for next person
  37. process_people(p, i + 1, n, sum_age, sum_weight);
  38. }
  39.  
  40. /*
  41. Recursive function to free allocated memory
  42. */
  43. void free_people(person *p[], int i, int n)
  44. {
  45. if (i == n)
  46. return;
  47.  
  48. free(p[i]);
  49.  
  50. free_people(p, i + 1, n);
  51. }
  52.  
  53. int main()
  54. {
  55. int n;
  56.  
  57. printf("Enter the number of people: ");
  58. scanf("%d", &n);
  59.  
  60. person *p[n];
  61.  
  62. int sum_age = 0;
  63. float sum_weight = 0;
  64.  
  65. // One recursion handles both input and sum
  66. process_people(p, 0, n, &sum_age, &sum_weight);
  67.  
  68. printf("\n------ Results ------\n");
  69. printf("Total Age = %d\n", sum_age);
  70. printf("Total Weight = %.2f\n", sum_weight);
  71.  
  72. printf("Average Age = %.2f\n", (float)sum_age / n);
  73. printf("Average Weight = %.2f\n", sum_weight / n);
  74.  
  75. // Free allocated memory
  76. free_people(p, 0, n);
  77.  
  78. return 0;
  79. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Enter the number of people: 
------ Results ------
Total Age = 0
Total Weight = 0.00
Average Age = -nan
Average Weight = -nan