Please check, I am getting errors. #include <stdio.h> #include <stdlib.h> //crea
ID: 3780657 • Letter: P
Question
Please check, I am getting errors.
#include <stdio.h>
#include <stdlib.h>
//creating struct for storing student id and percentage
struct student
{
int stuid;
int per;
} s[50];
//main program started
int main()
{
//declaring variables
char choice;
int count,i,j;
int n;
for(count=0; count<50; count++)
{ //for loop to read the grades till array size
printf("-------------------sorting --------------- Sorting(s) Quit(q) ");
scanf("%c",&choice);
if(choice == 's')
{ //if user choice is s, then read the id number and percentage
printf( "Enter id number");
scanf("%d", &s[count].stuid);
printf( "Enter grade:");
scanf("%d", &s[count].per);
//while loop for entering valid score
while(s[count].per>=0 && s[count].per<=100)
{
printf( "please enter a valid score between 0 to 100");
scanf("%d", &s[count].per);
}
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
n=count;
//sorting struct based on student id number
for (i = 1; i < n; i++)
for (j = 0; j < n - i; j++)
{
if(s[j].stuid> s[j+1].stuid)
{
temp = s[j].stuid;
s[j].stuid = s[j+1].stuid;
s[j+1].stuid = temp;
}
printf("student id and average scores are: ");
for(i=0; i<count; i++)
{
printf("%d %d", s[count].stuid, s[count].per);
}
return 0;
}
Explanation / Answer
Solution:
#include <stdio.h>
#include <stdlib.h>
//creating struct for storing student id and percentage
struct student
{
int stuid;
int per;
} s[50];
//main program started
int main()
{
//declaring variables
char choice;
int count,i,j;
int n;
int temp;
for(count=0; count<50; count++)
{ //for loop to read the grades till array size
printf("-------------------sorting --------------- Sorting(s) Quit(q) ");
scanf("%c",&choice);
if(choice == 's')
{ //if user choice is s, then read the id number and percentage
printf( "Enter id number");
scanf("%d", &s[count].stuid);
printf( "Enter grade:");
scanf("%d", &s[count].per);
//while loop for entering valid score
while(s[count].per>=0 && s[count].per<=100)
{
printf( "please enter a valid score between 0 to 100");
scanf("%d", &s[count].per);
}
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
n=count;
//sorting struct based on student id number
for (i = 1; i < n; i++)
for (j = 0; j < n - i; j++)
{
if(s[j].stuid> s[j+1].stuid)
{
temp = s[j].stuid;
s[j].stuid = s[j+1].stuid;
s[j+1].stuid = temp;
}
printf("student id and average scores are: ");
for(i=0; i<count; i++)
{
printf("%d %d", s[count].stuid, s[count].per);
}
return 0;
}
}