Introduce a number of students from keyboard and theirs marks - c

I need to introduce a no. of students , theirs name, surname and marks(3 marks). The average of the marks must be made, and then those who have passed must be displayed in the reverse order of their insertion.The problem is that, for example, i have 3 students i need to introduce 4 times in the structure to show me the result, and i need to have one after another, not with spaces or something else. Someone who can help me? Thanks!
#include <stdio.h>
#include <stdlib.h>
struct students
{
char name[100];
char surname[100];
float a,b,c;
};
int main()
{
int n,i,j;
scanf("%d",&n);
struct students s[n];
for(i=1;i<=n;i++)
{
scanf("\n%s %s %f %f %f\n",s[i].name,s[i].surname,&s[i].a,&s[i].b,&s[i].c);
}
for(j=n;j>=1;j--)
{
float m;
m=(s[j].a+s[j].b+s[j].c)/3;
if(s[j].a >= 5 && s[j].b >= 5 && s[j].c >= 5 && m >= 6)
{
printf("%s %s %.2f\n", s[j].name, s[j].surname, m);
}
}
return 0;
}

The problem is that you have an array of structures and you are indexing them wrongly.
Given you have n = 3, then you have an array of 3 structures indexed 0, 1 and 2.
First you need to change your structure reading for loop to this
for(i=0;i<n;i++) {
scanf("\n%s %s %f %f %f\n",s[i].name,s[i].surname,&s[i].a,&s[i].b,&s[i].c); }
For your next for loop, you need to change it to this
for(j=n - 1;j>=0;j--)
Hope this helps

Related

Wrong int values using struct and arrays [duplicate]

This question already has answers here:
What will happen if '&' is not put in a 'scanf' statement?
(6 answers)
Closed 4 years ago.
Hello I have a problem with integer. This is my code:
#include <stdio.h>
#include <stdlib.h>
struct data
{
char name[50];
int grade[1];
};
int main()
{
struct data persons[30];
int n = 3;
int i;
for(i=0;i<n;i++)
{
printf("Type person name nr: [%d] ",i+1);
scanf("%s",persons[i].name);
printf("Type grade: (from 1 to 6) ");
scanf("%d",persons[i].grade);
}
for(i=0;i<n;i++)
{
printf("Name [%d]: %s\n",i+1,persons[i].name);
printf("Grade [%d]: %d\n",i+1,persons[i].grade);
}
return 0;
}
And when I type some names and grades the output isn't correct:
This is my output
You are using an array for a single grade, when a standard int is enough.
struct data
{
char name[50];
int grade;
};
And then you also need to pass the reference of the int to scanf using an &.
scanf("%d", &persons[i].grade);
The corrected version of your program:
#include <stdio.h>
#include <stdlib.h>
struct data {
char name[50];
int grade; // In you case, to store one integer value just use int varibale because it seems more logical.
};
int main() {
struct data persons[30];
int n = 3;
int i;
for (i = 0; i < n; i++) {
printf("Type person name nr: [%d] ", i + 1);
scanf("%s", persons[i].name);
printf("Type grade: (from 1 to 6) ");
scanf("%d", &persons[i].grade); // To fill member of structure you may use '&' sign because scanf gets address.
}
for (i = 0; i < n; i++) {
printf("Name [%d]: %s\n", i + 1, persons[i].name);
printf("Grade [%d]: %d\n", i + 1, persons[i].grade);
}
return 0;
}
Also, keep in mind that compiler not always tell you that something is going to be wrong, in most cases using special flags (some of them I mentioned in the comment) for compiler can give you more information.
It's worth to note that current IDEs highlight obvious errors and really speed up your development process.
It's because grade is an array, so you need to do .grade[0]when writing or reading data to / from it, like so:
scanf("%d",persons[i].grade[0]);
...
printf("Grade [%d]: %d\n",i+1,persons[i].grade[0]);
you have to replace
printf("Grade [%d]: %d\n",i+1,persons[i].grade);
by
printf("Grade [%d]: %d\n",i+1,persons[i].grade[0]);
in the scanf you do scanf("%d",persons[i].grade); so because grade is a vector you give its address, but in the printf you have to specify the index else you print the address of the vector
However to use a vector is useless because it contains only one element, better to directly use an int for grade, and of course in that case you have to give &persons[i].grade for the scanf and persons[i].grade for
the printf
Execution :
Type person name nr: [1] a
Type grade: (from 1 to 6) 1
Type person name nr: [2] b
Type grade: (from 1 to 6) 2
Type person name nr: [3] c
Type grade: (from 1 to 6) 3
Name [1]: a
Grade [1]: 1
Name [2]: b
Grade [2]: 2
Name [3]: c
Grade [3]: 3

while loop asks user input one time only

#include <stdio.h>
#include <stdlib.h>
struct the_struct
{
char FirstName[20];
char LastName[32];
int Score[20];
};
int main ()
{
int i,n;
struct the_struct *ptr[100];
printf("how many students?\n");
scanf("%d",&n);
while (i<=n);
{
i==0;
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
i++;
}
}
hey guys, so when i enter the first input, it goes only once without going on for the number the user inputs, i tried the for loop but same result.
still learning C so my apology if i misunderstood something.
Thanks in advance.
Your while loop is problematic. You could rewrite it as:
for (i = 0; i < n; ++i)
{
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
}
And since you use %s to read and print Score, you should declare it as char Score[20]; instead of int.
The problem is that i is uninitialized. Therefore, the loop while (i <= n) has undefined behavior, and can end at any time.
Add int i = 0 initializer to fix this problem.
Notes:
i == 0 expression at the beginning of the loop has no effect
Since i starts at zero, your while loop should be while (i < n), not <=.
You should check the results of scanf to see if the user entered something meaningful
You should specify the size of the array into which you read a string, e.g. scanf("%31s",ptr[i]->LastName); This prevents buffer overruns.

Problems with arrays

I know this is going to be something of a silly slip or oversight on my behalf, but I can't get the array in this to print out correctly. When I run the code and put in my inputs, I get seemingly random numbers.
For example,
number of rooms was 1
wattage of lights was 2
hours used was 2
TV/computers was 2
The output I got was 3930804. What did I miss?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
int room[20] = {0.0};
int i;
int rooms = 0;
char option = 0;
int lights[20];
int hrsUsed[20];
int Telly_Computer[20];
printf("Enter number of rooms");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++)
{
printf("input wattage of lights");
scanf_s("%d", (lights+i));
printf("input number of hours use/day (average)");
scanf_s("%d", (hrsUsed+i));
printf("input number of TV/Computers");
scanf_s("%d", (Telly_Computer+i));
}
printf("%d \n", lights);
}
printf("%d \n", lights);
You're printing the array directly. You need to loop over it and print the elements one at a time.
int i;
for (i = 0; i < 20; ++i)
printf("%d\n", lights[i]);
You are just printing the address of lights (and using UndefinedBehavior by the way, address must be printed with %p). You must use a loop to print out all of the contents of each array slot.
for(int i=0;i<(sizeof(lights)/sizeof(int));i++)
printf("%d\n",lights[i]);

C programming return value odd

I tried to search this everywhere, but it's kind of difficult to word, it's most likely a simple fix. Basically when I go through my program that is supposed to compute the average rainfall for a year, it comes out with a very large number, however, I thought it may have been just that I was doing the arithmetic wrong or had a syntax error of some sort, but that was not the case, when I checked the value that the function returned it was the proper value.
#include <stdio.h>
#include <string.h>
void getData(float *, float *);
int main()
{
char state[2], city[81];
float rainFall[12], outputAverage, *pAverage;
printf("Name Here\n");
printf("Please enter the state using a two letter abreviation: ");
gets(state);
printf("Please enter the city : ");
gets(city);
pAverage = &outputAverage;
(getData(rainFall, pAverage));
printf("%.2f", outputAverage);
return (0);
}
void getData(float *rainFall, float *pAverage)
{
int i;
float total;
for (i=0; i<12; i++)
{
printf("Please enter the total rainfall in inches for month %d: ", i+1);
scanf("%f", &rainFall[i]);
total += rainFall[i];
}
*pAverage = total / 12;
}
you need to initialize total
float total = 0.0;
Initialize the total to 0
Why you make it complicated? Why not just
return total / 12 ?
and called it like
outputAverage = getData(rainfall)
This is a classic problem in C programming. You are mixing strings and numbers on the input. You are better off reading the input into a string and then, using sscanf to parse it properly.
You have uninitialized variable total which is taking garbage value, thus you see a very large answer.
changed your main.. have a look and let me know if you have understood what changes i have made?
#include <stdio.h>
#include <string.h>
void getData(float *);
int main(int argc, char*argv[])
{
char state[3]={0}, city[81]={0};
float outputAverage;
printf("Name Here\nPlease enter the state using a two letter abreviation: ");
scanf("%s",state);
printf("Please enter the city : ");
scanf("%s",city);
getData(&outputAverage);
printf("The Average Rainfall recorded for the year is %.2f\n", outputAverage);
return 0;
}
void getData(float *pAverage)
{
int i;
float rainFall[12]={0}, total=0;
for (i=0; i<12; i++)
{
printf("Please enter the total rainfall in inches for month %d: ", i+1);
scanf("%f", &rainFall[i]);
total += rainFall[i];
}
*pAverage = total / 12;
}
However instead of using gets you should use fgets but i forgot how to counter the issue of using simultaneous fgets to read input from the standard input stream.
Also initialize the total variable as you are adding in the loop new values to existing value in that variable which would not necessarily add to zero as the premier element. so it could be any garbage value + loop values.
I understand you are practicing pointer concept so you passed the address of the array of floats to your second function but if the rainfall function is not useful in main, Better to restrict the same where it would be useful

Expression must have class type error

I'm working on a homework assignment and I've hit a brick wall. I think I have all of the code that I need, I just need to get the program to compile. The object of the assignment is
Create a structure to hold student names and averages. The structure should contain a first name, last name and an integer grade average.
Then:
Write a program that will do the following:
1.) Create an array of pointers to these student structures.
2.) Prompt the user for names and averages.
3.) After you get the student’s information use malloc to provide the memory to store the information.
4.) Place the address of the student, returned by malloc, into the pointer array.
5.) AFTER the user indicates there are no more students:
Search the data entered and find the highest and lowest grade
average.
a)Print the name and grade for the highest grade
b)Print the name and grade for the lowest grade
c)Print the average of all grades entered
Here is my code:
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#define SIZE 25
int enterStudents (int ePointArray[SIZE]);
void searchData (int *sPointArray, int *sHigh, int *sLow);
int calculateAvg (int, int *avgPointArray);
void printData (int, int *pHigh, int *pLow);
struct student
{
char firstName[20];
char lastName[20];
int average;
};
int main()
{
int pointArray[SIZE], high[3], low[3];
int i = 0, studentCounter, avgGrade;
for (i = 0; i < SIZE; i++)
pointArray[i] = 0;
studentCounter = enterStudents(pointArray);
searchData(pointArray, high, low);
avgGrade = calculateAvg(studentCounter, pointArray);
printData(avgGrade, high, low);
return 0;
}
int enterStudents (int ePointArray[SIZE])
{
char tempFname[20], tempLname[20], yesNo[2] = "y";
int tempAvg, counter = 0;
int *studPtr;
struct student aStud={"\0", "\0", 0};
while( counter < SIZE && strcmp(yesNo, "y")==0)
{
printf(" Enter first name: ");
scanf("%s", tempFname);
printf(" Enter last name: ");
scanf("%s", tempLname);
printf(" Enter grade average:");
scanf("%d", tempAvg);
strcpy(aStud.firstName, tempFname);
strcpy(aStud.lastName, tempLname);
aStud.average = tempAvg;
studPtr = malloc(sizeof(struct student));
ePointArray[counter] = *studPtr;
counter++;
printf("/n");
printf(" Do you have more students? yes or no:");
scanf("%s", yesNo);
}
return counter;
}
void searchData (int sPointArray[SIZE], int sHigh[3], int sLow[3])
{
int searchCounter = 0;
while( searchCounter = 0)
{
if( *sPointArray[searchCounter].average > *sPointArray[searchCounter+1].average)
{
sHigh[0] = &sPointArray[searchCounter].firstName;
sHigh[1] = &sPointArray[searchCounter].lastName;
sHigh[2] = &sPointArray[searchCounter].average;
}
if( *sPointArray[searchCounter].average < *sPointArray[searchCounter+1].average)
{
sLow[0] = &sPointArray[searchCounter].firstName;
sLow[1] = &sPointArray[searchCounter].lastName;
sLow[3] = &sPointArray[searchCounter].average;
}
searchCounter++;
}
}
int calculateAvg( int totalStudents, int avgPointArray[SIZE])
{
int sum = 0;
int avgCounter;
double overallAvg;
for( avgCounter = 0; avgCounter < totalStudents; avgCounter++)
sum = sum + *avgPointArray[avgCounter].average;
overallAvg = sum/totalStudents;
return overallAvg;
}
void printData (int pAverage, int pHigh[3], int pLow[3])
{
printf(" Highest Grade: %s %s %d", pHigh[0], pHigh[1], pHigh[3]);
printf("/n");
printf(" Lowest Grade: %s %s %d", pLow[0], pLow[2], pLow[3]);
printf("/n");
printf(" Average Grade: %d",pAverage);
}
The main chunk of problems come from the searchData function. In the if statements, every occurrence of *sPointArray and &sPointArray is underlined in red and the error reads
"Error: expression must have class type"
The same thing also happens in the calculateAvg function with *avgPointArray in the for loop. I know that the error is a fairly common problem for noobie C programmers (i.e myself) and that it generally has to do with writing the code as a function instead of a statement or something like that, but I can't for the life of me find where I have went wrong. Any help would be highly appreciated. I've been working at this for so long my vision is blurring.
Also, for anyone who solves this in like two seconds and wants proof that I'm a true idiot, there is an error in the enterStudents function where it says StudPtr = malloc(sizeof...). The error shows under the assignment symbol and says
"Error: a value of type "void*" cannot be assigned to an entity of type "int*".
I understand this concept in theory, but some advice for how to fix it would be highly appreciated.
Thank you in advance for any help.
You declare the sPointArray as an array of integers, but use it as an array of structures.

Resources