the question is to calculate the average of each student separately and then show the id and the average of rank one student. how to compare members of structure
#include<stdio.h>
typedef struct student
{
int id;
float math,physics;
float av;
}std;
int main()
{
int i;
std p[5];
for(i=0;i<5;i++)
{
printf("enter student(%d) id: ",i+1);
scanf("%d",&p[i].id);
printf("grade of math over 100: ");
scanf("%f",&p[i].math);
printf("grade of physics over 100: ");
scanf("%f",&p[i].physics);
printf("average=%.3f\n\n",(p[i].math+p[i].physics)/2);
}
}
To compare on element with another you would take either
p[index]->av {comparaision} p[index]->av
Example p[0]->av > p[1]->av
Don't forget printf("average=%.3f\n\n",(p[i].math+p[i].physics)/2); will print you the result of av but will not save it in p. Save it in p[index].av to be able to do comparaisons.
Then afterward just do a loop where you compare each of them and save their id in an array. The array should be based on a decreasing average with the matching id. Then just print the array and you will be good to go.
#include<stdio.h>
typedef struct studentd
{ int id;
float math,physics;
float av;
} std;
int main()
{
int i,a;
std p[5];
for(i=0; i<5; i++)
{
printf("student(%d) id: ",i+1);
scanf("%d",&p[i].id);
printf("grade of math over 100: ");
scanf("%f",&p[i].math);
printf("grade of physics over 100: ");
scanf("%f",&p[i].physics);
printf("average=%.3f\n\n",p[i].av=(p[i].math+p[i].physics)/2);
}
int max=p[0].av;
for(i=0; i<5; i++)
{
if(p[i].av<=p[i+1].av)
{
max=p[i].av;
}
}
printf("the highest average is for student: %d ",p[i].id);
return 0;
}
/*END*/
/now this is the updated code my problem is how to link the id of student to the max to show the id of student whi got the highest mark/
Well one of two things,
Either add an integer to track the index of the structure containing the max,
Or instead of
max =p[i].avg
Use max = p[i]
Of course let max be a struct not float or int
Related
#include <stdio.h>
int i, n;
struct add_stock
{
char fullname[30];
int stocks;
char com_name[30];
int shares;
float price;
float total;
int totalmoney;
} add;
int main()
{
printf("Enter full name : ");
scanf(" %[^\n]s", add.fullname);
printf("Enter the no. of stocks you want to purchased : ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the name of the company : ");
scanf(" %[^\n]s", add[i].com_name);
printf("Enter the no. of shares you want to purchased : ");
scanf("%d", &add[i].shares);
printf("Enter the price of each share : ");
scanf("%f", &add[i].price);
add.total = add.shares * add.price;
printf("Toatl money invested in this stock : ");
scanf("%f", &add[i].total);
}
printf("Total money invested : ");
scanf("%d", add.totalmoney);
return 0;
}
In question it's add_stock , not add stock , i write like this becoz it's not accepting question.
So, i get error for "add" saying subscripted value is neither array nor pointer nor vector.
To declare an array of strucuture, you need to define the variable as below,
struct add_stock
{
char fullname[30];
int stocks;
char com_name[30];
int shares;
float price;
float total;
int totalmoney;
} add[20];
this makes the add as an array of add_stock elements.
then you can access it as, add[0].total, add[1].price and so on.
If you want to declare an array that need to be having dynamic number of elements, you can do so as below.
struct add_stock* arStock;
//allocate memory to hold 10 elements
arStock = (add_stock*)malloc( 10 * sizeof(struct add_stock));
arStock[0]->total=10; //access it with ->, instead of .
I had came across a problem that I have tried so many times with different ways but still not able to obtain the required solution please do help me.
PROBLEM: Define a structure to store students’ details. Pass them to a function where the student with HIGHEST CGPA is calculated from a set of 5 students. And display the result.(Here we have to store name, age and CGPA obtained of each student)
Here is my try at the problem:
#include <stdio.h>
void highCGPA(float b,struct detst D[4]);
struct detst
{
int age;
float CGPA;
char name[30];
};
int main()
{
struct detst D[4];
int i;
float h;
for(i=0;i<=4;i++)
{
printf("Enter the name of student %d:\n",i+1);
scanf("%s",&D[i].name);
printf("Enter the age of student %d:\n",i+1);
scanf("%d",&D[i].age);
printf("Enter the CGPA obtined by student %d:\n",i+1);
scanf("%f",&D[i].CGPA);
}
highCGPA(h,D);
}
void highCGPA(float b,struct detst D[4])
{
int i,max;
max = D[0].CGPA;
for(i=0;i<=4;i++)
{
if(D[i].CGPA > max)
{
max = D[i].CGPA;
}
}
printf("Highest CGPA obtained is:\n%f",max);
}
There is more than one problem. You're trying to store the data of 5 students in an array of struct with size 4. So:
struct detst D[5]; // fixed size
int i;
float h;
for(i=0;i<5;i++) { // EDIT (comments suggestion): for loop fix following standard convetions
/* take input */
}
Lastly, if you declare max as an int, you can't try to print it with a format specifier for float. So:
printf("Highest CGPA obtained is: %d\n",max); // format specifier for int is %d (not %f)
There are couple of other problems.
your declaration of funtion highCGPA is above your struct detst definition
you should have got error
error: array type has incomplete element type ‘struct detst’
declare your function after the structure definition.
your max variable is int in the function highCGPA , but you are trying to store a float value in it.
With a sligth change to program functionallity can be improved:
#include <float.h> // FLT_MAX
#include <stdio.h>
struct detst
{
int age;
float CGPA;
char name[30];
};
// Return offset of student with highest CGPA
int highCGPA(struct detst const (*D)[5]); // Using pointer to array
// to avoid degeneration
int main()
{
struct detst D[5];
int i;
for(i = 0; i < 5; i++)
{
printf("Enter the name of student %d:\n", i + 1);
scanf("%29s", D[i].name); // Make sure we don't overwrite the buffer
printf("Enter the age of student %d:\n", i + 1);
scanf("%d", &D[i].age);
printf("Enter the CGPA obtained by student %d:\n", i + 1);
scanf("%f", &D[i].CGPA);
}
int bestStudentOffset = highCGPA(&D); // By asking for best student
// we can obtain a lot more
printf(
"Best student is %d year old %s with\n",
D[bestStudentOffset].age,
D[bestStudentOffset].name);
printf("Highest CGPA obtained is:\n%f\n", D[bestStudentOffset].CGPA);
}
// Return offset of student with highest CGPA
int highCGPA(struct detst const (*D)[5])
{
int i, maxOffset = -1;
float max = -FLT_MAX;
for(i = 0; i < 5; i++)
{
if((*D)[i].CGPA > max)
{
max = (*D)[i].CGPA;
maxOffset = i;
}
}
return maxOffset;
}
How to get the max value in a structure? I have tried to create a simple program but I'm having issues with the if statement or variable, since I cannot determine the winner or candidate number which has the highest score.
#include<stdio.h>
#include<conio.h>
struct Candidate{
float Score;
short Number;
}candidate1[5];
main(){
int i,n,highest;
for(i=0;i<5;i++){
printf("Candidate Number: ");
scanf("%i",&candidate1[i].Number);
printf("Score: ");
scanf("%i",&candidate1[i].Score);
highest=candidate1[i].Score;
for (n=0;n<5;n++)
if (candidate1[i].Score>highest);
}
printf("Highest Number: %i\n",highest);
system("pause");
}
fix like this
#include <stdio.h>
#include <stdlib.h>
struct Candidate {
float Score;
short Number;
}candidate1[5];
int main(void){
int i, n, highest = 0;
n = sizeof(candidate1)/sizeof(*candidate1);
for(i=0;i<n;++i){
printf("Candidate Number: ");
scanf("%hi", &candidate1[i].Number);
printf("Score: ");
scanf("%f",&candidate1[i].Score);
if(candidate1[highest].Score < candidate1[i].Score)
highest = i;
}
printf("Highest Number: %f\n", candidate1[highest].Score);
system("pause");
return 0;
}
,
The most common idiom for finding the max of type <T> (double, int, whatever) from an array of structs <S> goes as follows
<S> array[numElements]; //defined and allocated earlier. Has a score `<T> score`
<T> bestScore = array[0].score;
int bestIndex = 0;
int i;
for(i=1;i<numElements;i++) {
if(array[i].score>bestScore) {
bestIndex = i;
bestScore = array[i].score;
}
}
//do things with bestScore and array[bestIndex];
If you have a 2D array you can replace the single for-loop with a double for loop, and use an additional bestIndex variable for the second dimension.
If the array may contain 0 elements it is sometimes common to set bestScore to a minimum possible value and loop from 0 to numElements.
My program reads the following data: Date, Distance and Time.
So for example an input would look like:
Date: 10.10.2013
Distance (m): 500
Time (HH:MM:SS): 01:20:05
I want to store all this information in an array. The problem is that I want the user to input date, distance and time several times and the program has to save all the data in an array.
I can't store it like this, because then how would I know which index is the date index? And how should I store the time? I can't store it with :.
arr[0] = 10.10.2013
arr[1] = 500
arr[2] = 012005
arr[3] = 22.10.2013
arr[4] = 200
arr[5] = 000510
You can make a struct:
struct Data{
Date date;
Distance distance;
Time time;
}
Then declare an array of Data and use it like that:
Data arr[5];
arr[0].date = //some date;
arr[0].distane =//some distance
arr[0].time=//some time
Because the type of data you will need to store, it needs type char, so it can be stored in strings. (i.e. "10.10.2013")
First, Define a struct PARAM:
typedef struct {
char date[20];
char distance[20];
char time[20];
} PARAM;
use PARAM to create an array of your struct:
PARAM param[20];
Now, you can use it like this for example:
int main(void)
{
strcpy(param[0].date, "10.10.2013");
strcpy(param[0].time, "05:02:10");
strcpy(param[0].distance, "500");
//and so on for all the struct array elements, 0 through 20
return 0;
}
Or, better yet, using printf() and scanf() statements as necessary, you can prompt the user for input in a loop, and store in your struct array:
int main(void)
{
int i;
for(i=0;i<20;i++)
{
printf("enter date %d:", i+1);
scanf("%s", param[i].date);
printf("enter distance %d:", i+1);
scanf("%s", param[i].distance);
printf("enter time %d:", i+1);
scanf("%s", param[i].time);
}
return 0;
}
EDIT Regarding question in comment Therefore I guess its best to store them in date.day, date.month and date.year. Right? That approach would work, and I include it below, but it is a little more tedious to enter data that way. I included a second example below that might improve both, entering data, and storing data.
So, Per your comment, two ways jump to mind:
ONE, create struct members that contain the discrete members of time and date as integers: i.e.
typedef struct {
int day;
int month;
int year;
int hour;
int minute;
int second;
}TIMEDATE;
Use this struct as a member of the PARAM struct;
typedef struct {
int distance;
TIMEDATE timedate;
}PARAM;
PARAM param[20];
Now, just modify and expand the example of the last main() function to include scanning in values for the new struct members. This will be more tedious for the person using your program, but will allow you to keep all the input values as numbers as you have indicated.
//Note the changes in scanf format specifiers for int, "%d":
// in all the statements
int main(void)
{
int i;
for(i=0;i<20;i++)
{
printf("enter date %d:", i+1);
scanf("%d", ¶m[i].timedate.day);
printf("enter time %d:", i+1);
scanf("%d", ¶m[i].timedate.month);
printf("enter time %d:", i+1);
scanf("%d", ¶m[i].timedate.year);
printf("enter time %d:", i+1);
scanf("%d", ¶m[i].timedate.hour);
printf("enter time %d:", i+1);
scanf("%d", ¶m[i].timedate.minute);
printf("enter time %d:", i+1);
scanf("%d", ¶m[i].timedate.second);
printf("enter time %d:", i+1);
scanf("%d", ¶m[i].distance);
}
return 0;
}
Two, modify the first approach to include using strings AND integers, all in the same struct. This will make it easier for the user user to enter time and date information, and possible for you to manipulate the data easier. And a bonus, it will demonstrate how to parse the user input string data into integer data.
typedef struct {
char date[20];//keep as char
char time[20];//keep as char
int distance; //changed to int
TIMEDATE timedate;//container for in data
} PARAM;
//use PARAM to create an array of your struct:
PARAM param[20], *pParam; //create a pointer to pass
int GetIntData(PARAM *p, int index);//prototype for new function
//Note the changes in scanf format specifiers for int, "%d":
// in all the statements
int main(void)
{
int i, loops;
pParam = ¶m[0]; //initialize pointer to struct
printf("How many sets of data would you like to enter? :");
scanf("%d", &loops);
for(i=0;i<loops;i++)
{
printf("enter date (eg:MM.DD.YYYY): %d:", i+1);
scanf("%s", pParam[i].date);
printf("enter time (eg HH:MM:SS): %d:", i+1);
scanf("%s", pParam[i].time);
printf("enter distance %d:", i+1);
scanf("%d", &pParam[i].distance);
GetIntData(pParam, i);
}
return 0;
}
//reads string members into integer members
int GetIntData(PARAM *p, int index)
{
char *buf=0;
if(strstr(p[index].date, ".")==NULL) return -1;
p[index].timedate.month = atoi(strtok(p[index].date, "."));
p[index].timedate.day = atoi(strtok(NULL, "."));
p[index].timedate.year = atoi(strtok(NULL, "."));
if(strstr(p[index].time, ":")==NULL) return -1;
buf=0;
p[index].timedate.hour = atoi(strtok(p[index].time, ":"));
p[index].timedate.minute = atoi(strtok(NULL, ":"));
p[index].timedate.second = atoi(strtok(NULL, ":"));
return 0;
}
I need help on two questions, Its not homework but its to study for an exam. I need to have these questions because i was allowed 1 full page of notes for the exam. If you could help me these two simple questions for me that would be great. Here are the questions:
"Write a function called getGrades. The function that repeatedly prompts the user for positive integers until the user enters a negative value to stop. The function should return the average of these grades and the highest grade."
"Write a function called Get_Info that takes a pointer to a student structure, (that has three fields: char array called name, an int id, and a double gpa) as its only argument. The function prompts the user for the required information to fill the structure and stores it in the appropriate fields."
What I have so far, Let me know if they are correct and if i need to add anything.
1.
double getGrades() {
double average;
double i;
For(i=1 ; i<i; i++)
{
printf("Enter Grade1:\n");
scanf("%lf", &i);
}
if (i<0)
{
(double) average == (grade1 + grade2 + grade3) / 3;
return average;
}
}
2.
typedef struct {
int id;
double gpa;
char name[SIZE];
} student;
void Get_Info(student list[], int num) {
int i;
for(i=0; i<num; i++) {
printf("\nName:%s", list[i].name);
printf("\nGPA:%lf", list[i].gpa);
printf("\nID: %d\n", list[i].id);
}
}
On #1: The requirement is that the function accept ints. You are scanning for doubles.
The requirement is "The function should return the average of these grades and the highest grade." You only return one double, when two different outputs are called for.
Your for loop is written as "For" (C is case-sensitive), and is based on the test i<i. When will i ever be less than itself??
Here's my version of it.
double getGrades(int* max)
{
int sum = 0;
int input;
int i = 0;
*max = 0;
printf("Enter Grade #%d:\n", i+1);
scanf("%d", &input);
while (input > 0) {
if (*max < input) {
*max = input;
}
sum = sum + input;
i++;
printf("Enter Grade #%d:\n", i+1);
scanf("%d", &input);
}
return i? ((double)sum / i) : 0;
}
Your #2 is much better than your #1, but still has some errors:
The requirement is that the function takes a pointer to a student struct, NOT an array.
It should then print a series of Prompts, and get a series of answers (just as you did in #1).
This is a sequence of printf/scanf.
And when using scanf, you typically pass the ADDRESS of the variable, using &.
(strings are a exception, however)
Here is my version:
typedef struct {
char name[SIZE];
int id;
double gpa;
} student;
void Get_Info(student* ps) {
printf("Enter Name\n");
scanf("%s", ps->name);
printf("Enter ID:\n");
scanf("%d", &ps->id);
printf("Enter GPA\n");
scanf("%lf", &ps->gpa);
}
Try this. It should seem intuitive enough:
double getGrades() {
double average;
double grade;
double total = 0;
int count = 0;
while (1) {
printf("Enter grade: ");
scanf("%d", &grade);
if (grade < 0) {
if (count == 0) {
average = 0;
break;
}
average = total/count;
break;
}
count++;
total += grade;
}
return average;
}