Answer to Question #177962 in C for Tejareddy.Y

Question #177962

Mr.x was making noise in the class.so,he was guven the task to arrange the boxes in an order.Each box is placed in each room. The teacher told him to arrange in ascending order.he has to compare the size of the box and arrange them.help mr X in the logic of sorting and generate a c application for the same.

Requirements:-

1.read the number of boxes.

2.read the size of the boxes

3.display the size of boxes after sorting


1
Expert's answer
2021-04-03T04:17:49-0400
#include <stdio.h>


#define MAX_BOXES 100


int ReadBoxex(int boxes[], int size) {
    int n=0, i, box;
    while (n<=0 || n > MAX_BOXES) {
        printf("How many boxes? ");
        scanf("%d", &n);
        if (n<=0) {
            printf("I can't sort negative number of boxes. Try again.\n");
        }
        if (n > MAX_BOXES) {
            printf("Too many boxes, I can sort less than %D only\n", MAX_BOXES);
        }
    }


    for (i=0; i<n; i++) {
        printf("Size of box in room %d: ", i+1);
        box = -1;
        while (box <=0) {
            scanf("%d", &box);
            if (box <= 0) {
                printf("Negative box, really?\n");
                printf("Try again: ");
            }
        }
        boxes[i] = box;
    }
    return n;
}


void SortBoxes(int boxes[], int size) {
     int i, j, min_box, box;


     for (i=0; i<size-1; i++) {
        min_box = i;
        for (j=i+1; j<size; j++) {
            if (boxes[j] < boxes[min_box]) {
                min_box = j;
            }
        }
        box = boxes[i];
        boxes[i] = boxes[min_box];
        boxes[min_box] = box;
     }
}


void DisplayBoxes(int boxes[], int size) {
    int i;


    printf("Sorted boxes:\n");
    for (i=0; i<size; i++) {
        printf("Room %3d: %4d\n", i+1, boxes[i]);
    }
}


int main() {
    int boxes[MAX_BOXES];
    int num_boxes;


    num_boxes = ReadBoxex(boxes, MAX_BOXES);
    SortBoxes(boxes, num_boxes);
    DisplayBoxes(boxes, num_boxes);


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS