In: Computer Science
1) Define a C struct that can be used to represent an ingredient in a recipe. You must include the ingredient, the amount to use, and the unit of measurement. When allocated, the struct must be self-contained; do not rely on information being stored anywhere else in memory.
2) Define a C function that will print an array of ingredients to the standard output stream, one per line. You must use the struct definition from the first part.
3) Define a C function that will sort an array of ingredients, alphabetically, using the selection sort algorithm. You must use the struct definition from the first part, and you must use the selection sort algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ingredient {
char name[100];
int amount;
char unit[100];
};
void print(struct ingredient arr[], int n) {
for (int i = 0; i < n; ++i) {
printf("%s : %d %s\n", arr[i].name, arr[i].amount, arr[i].unit);
}
}
void swap(struct ingredient *xp, struct ingredient *yp) {
char temp1[100];
strcpy(temp1, xp->name);
int temp2 = xp->amount;
char temp3[100];
strcpy(temp3, xp->unit);
strcpy(xp->name, yp->name);
xp->amount = yp->amount;
strcpy(xp->unit, yp->unit);
strcpy(yp->name, temp1);
yp->amount = temp2;
strcpy(yp->unit, temp3);
}
void sort(struct ingredient arr[], int n) {
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++) {
if (strcmp(arr[j].name, arr[min_idx].name) < 0)
min_idx = j;
}
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
int main() {
struct ingredient arr[2];
strcpy(arr[0].name, "pepper");
arr[0].amount = 40;
strcpy(arr[0].unit, "gms");
strcpy(arr[1].name , "chilli");
arr[1].amount = 20;
strcpy(arr[1].unit , "gms");
printf("Before Sorting:\n");
print(arr,2);
sort(arr,2);
printf("\nAfter Sorting:\n");
print(arr,2);
return 0;
}
OUTPUT: