Please complete the code. The items that need completing are outlined with comme
ID: 3781965 • Letter: P
Question
Please complete the code. The items that need completing are outlined with comments.
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
struct student{
int id;
int score;
};
void sort(struct student* students, int n){
/*Sort the n students based on their score*/
}
int main(){
/*Declare an integer n and assign it a value.*/
/*Allocate memory for n students using malloc.*/
/*Generate random and unique IDs and random scores for the n students, using rand().*/
/*Print the contents of the array of n students.*/
/*Pass this array along with n to the sort() function*/
/*Print the contents of the array of n students.*/
return
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
struct student{
int id;
int score;
};
void sort(struct student* students, int n){
/*Sort the n students based on their score*/
}
int main(){
/*Declare an integer n and assign it a value.*/
/*Allocate memory for n students using malloc.*/
/*Generate random and unique IDs and random scores for the n students, using rand().*/
/*Print the contents of the array of n students.*/
/*Pass this array along with n to the sort() function*/
/*Print the contents of the array of n students.*/
return 0;
}
0;
}
Explanation / Answer
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
struct student
{
int id;
int score;
};
void sort(struct student* students, int n){
/*Sort the n students based on their score*/
int i, j;
struct student temp;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < (n - 1-i); j++)
{
if ((students+j)->score < (students+j+1)->score)
{
temp = *(students+j);
*(students+j)= *(students+j+1); //swapping of values in bubble sort
*(students+j+1) = temp;
}
}
}
}
int main()
{
/*Declare an integer n and assign it a value.*/
int n =5;
int i;
/*Allocate memory for n students using malloc.*/
struct student *ptr = (struct student*)malloc(n*sizeof *ptr);
/*Generate random and unique IDs and random scores for the n students, using rand().*/
printf(" student scores");
for(i=0;i<n;i++)
{
(ptr+i)->id = rand()%1000 +1;
(ptr+i)->score = rand()%100 +1;
}
/*Print the contents of the array of n students.*/
for(i=0;i<n;i++)
{
printf(" %d %d",(ptr+i)->id,(ptr+i)->score);
}
/*Pass this array along with n to the sort() function*/
sort(ptr,n);
/*Print the contents of the array of n students.*/
printf(" Scores after sorting from highest to lowest");
for(i=0;i<n;i++)
{
printf(" %d %d",(ptr+i)->id,(ptr+i)->score);
}
return 0;
}
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.