Small Triangles, Large Triangles in C hackerrank solution

      

  #include <stdio.h>           
  #include < stdlib.h> 
  #include <math.h> 
  
  struct Triangle {
      int a;
      int b;
      int c;
  };
  
  double calculate_area(struct Triangle t) {
      double p = (t.a + t.b + t.c) / 2.0;
      return sqrt(p * (p - t.a) * (p - t.b) * (p - t.c));
  }
  
  int compare_triangles(const void* a, const void* b) {
      struct Triangle* triangleA = (struct Triangle*)a;
      struct Triangle* triangleB = (struct Triangle*)b;
  
      double areaA = calculate_area(*triangleA);
      double areaB = calculate_area(*triangleB);
  
      if (areaA < areaB) {
          return -1;
      } else if (areaA > areaB) {
          return 1;
      } else {
          return 0;
      }
  }
  
  void sort_triangles(struct Triangle* triangles, int n) {
      qsort(triangles, n, sizeof(struct Triangle), compare_triangles);
  }
  
  int main() {
      int n;
      scanf("%d", &n);
  
      struct Triangle* triangles = malloc(n * sizeof(struct Triangle));
  
      for (int i = 0; i < n; i++) {
          scanf("%d %d %d", &triangles[i].a, &triangles[i].b, &triangles[i].c);
      }
  
      sort_triangles(triangles, n);
  
      for (int i = 0; i < n; i++) {
          printf("%d %d %d\n", triangles[i].a, triangles[i].b, triangles[i].c);
      }
  
      free(triangles);
  
      return 0;
  }
  
  
  

Let's break down the code step by step:

We include the necessary header files: for input/output, for memory allocation, and for the square root function.

We define a structure called Triangle to represent each triangle. It has three sides: a, b, and c.

We define a function called calculate_area() that takes a Triangle as input and calculates its area using Heron's formula.

We define a comparison function called compare_triangles() that compares two triangles based on their areas. This function is used by the qsort() function to sort the triangles.

We define a function called sort_triangles() that takes an array of triangles and its size as input and sorts the triangles in ascending order based on their areas using the qsort() function.

In the main() function, we read the number of triangles n from the user.

We dynamically allocate memory for an array of n triangles using malloc().

We use a loop to read the side lengths of each triangle from the user and store them in the array of triangles.

We call the sort_triangles() function to sort the triangles based on their areas.

Finally, we iterate over the sorted array of triangles and print their side lengths.

We free the dynamically allocated memory using free().

The code uses the concepts of structures, dynamic memory allocation, function pointers, and the qsort() function from the C standard library to solve the problem. By providing the expected input and executing the code, you should see the triangles sorted in ascending order of their areas, as specified in the problem statement.