Sort by using Structure's arrays - c

So I want to sort the list so that i can give them their position according to their grades but it's not working.
It is Showing error like : incompatible types when assigning to type char from type struct info.
p.s : I am trying to do this sorting using Structures.
#include <stdio.h>
#define SIZE 3
struct info {
char name[20];
int number;
double grade;
};
int main(void) {
struct info list[SIZE];
int i, j;
char temp;
int avg;
for (i = 0; i < SIZE; i++) {
printf("Enter your name : ");
scanf("%s", list[i].name);
printf("Enter your number : ");
scanf("%d", & list[i].number);
printf("Enter your grade : ");
scanf("%lf", & list[i].grade);
}
for (i = 0; i < SIZE; i++) {
printf("Name : %s Student Number : %d Grade : %f", list[i].name,
list[i].number, list[i].grade);
printf("\n");
}
for (i = 0; i < SIZE; i++) {
for (j = i + 1; j < SIZE; j++) {
if (list[j].grade > list[i].grade) {
temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
for (i = 0; i < SIZE; i++) {
printf("%d st Position : Name : %s Student Number : %d Grade : %f ",i,
list[i].name, list[i].number, list[i].grade);
printf("\n");
}
avg = 0;
for (i = 0; i < SIZE; i++)
avg += list[i].grade;
avg = avg / 3;
printf("Average is %d", avg);
getch();
return 0;
}
errors are in the following code:
for(i=0;i<SIZE;i++) {
for(j=i+1;j<SIZE;j++) {
if(list[j].grade>list[i].grade) {
temp=list[j];
list[j]=list[i];
list[i]=temp;
}
}
}

You assign a type char with name temp and try to assign a struct to it. Instead create a struct temp and then sort your array of structs.
#include <stdio.h>
#define SIZE 3
struct info { // use typedef struct info instead
char name[20];
int number;
double grade;
};
int main(void) {
struct info list[SIZE]; // allows you to write info list[size]
int i, j; // do not initialize loop variables outside of their loops unless you need to(makes it easier to read the loop statements/spot mistakes)
char temp; // you need to use a type info, not char e.g. info temp
I can not compile it myself at the moment, so please let us know in the comments if you have any further questions.

Related

Structures for C programming

Here is the current code. For averaging gradesa from 3 students. Underneath the code are the errors im facing. Was able to work them down from 25 to 4.
Visual studio is saying i have an unidentified expression E0029, E0020, C2065, C2109
dont believe im using pointers as we were told not use them. Read the error codes and looked them but cant determine where im falling short.
Thank you in advanced.
#include <stdio.h>
#define N 5
struct student {
char firstName[50];
int roll;
float marks[3];
}s[N];
typedef struct {
char firstName[50];
int roll;
float marks[3];
}student_t;
int main() {
int i;
double total = 0;
double marks_avg ;
student_t personA, personB, SMCstudent[N];
SMCstudent->marks[0] = 99;
personA= { "Daniel",10 {100,98,90}
};
printf("Enter information of student:\n");
//storing
for (i = 0;i < N;++i); {
s[i].roll = i + 1;
printf("\nFor all number %d,\n", s[i].roll);
printf("Enter first name:");
scanf_s("%s", &s[i].marks);
}
printf("Enter 3 marks");
for (int j = 0; j < 3; j++) {
printf("enter grade\n");
scanf_s("%f", s[i].marks[j]);
scanf_s("%f", & array[i]);
}
for (i = 0; i < N; i++) {
total += s[i].marks[2];
}
marks_avg = total / N;
printf("average grade for 5 students is %f\n\n", marks_avg);
printf("displaying information:\n\n");
return 0;
}
#RetiredNinja claims that you can only do a structure assignment during initialization.
This is simply not true.
You need to specify the type name as well, but this code is valid:
personA = (student_t){ "Daniel", 10, {100.f,98.f,90.f} };
This is assigning a "compound literal" to a structure.
(l-value personA is the structure, and the right side, (student_t){...} is the compound literal)
Example, working code:
#include <stdio.h>
typedef struct {
char firstName[50];
int roll;
float marks[3];
}student_t;
int main(void) {
student_t personA;
personA= (student_t){ "Daniel",10, {100.f,98.f,90.f} };
printf("%s(%d): %.2f %.2f %.2f", personA.firstName, personA.roll,
personA.marks[0], personA.marks[1], personA.marks[2]);
return 0;
}

I am having hard time taking pointer structure as a function's parameter in C. I am a beginner and I am confused

#include<stdio.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create* storage[3]);
int main()
{
for(int j = 0; j<4; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
float sum = givename(&Create);
printf("%f", sum);
}
}
float givename(struct create* storage[3])
{
for(int i = 0; i<4; ++i)
{
storage[i]->total = storage[i]->a + storage[i]->b + storage[i]->c;
return storage[i]->total;
}
}
This is something I wrote and of course it doesn't work, it might seem stupid to elitist C programmers but a help would be appreciated. I wanted to take an input into array of structure and then use it inside a function that has been called by reference.
Please tell me can someone help me show what I am misunderstanding with the logic ?
The function
float givename(struct create* storage[3])
takes an array of pointers to struct create, you are sending the address of an array of struct create. If you want an array of pointers to struct create, do it like this:
struct create * array[3];
array[0] = & Create[0];
array[1] = & Create[1];
array[2] = & Create[2];
Plus, this function stops during the first iteration, because of the return.
Array's size is 3, you're looping 4 times.
Your main needs a return value;
If you wanted to pass the whole array to givename (an array of struct create, not pointers), you don't need to since Create is global;
For each iteration in the first loop (3 after fixing), you iterate the whole array, I doubt this is what you wanted to do.
The following version prompts to fill 3 struct create, computes the total for each (and stores it), and prints it.
Is this what you wanted to do ?
#include<stdio.h>
#include <stdlib.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create * storage);
int main()
{
for(int j = 0; j < 3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", & Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", & Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", & Create[j].c);
float sum = givename(& Create[j]);
printf("%f\n", sum);
}
return EXIT_SUCCESS;
}
float givename(struct create * storage)
{
storage->total = storage->a + storage->b + storage->c;
return storage->total;
}
echo 1 2 3 4 5 6 7 8 9 | yourProgram
>> Input a[1]:Input b[1]:Input c[1]:6.000000
>> Input a[2]:Input b[2]:Input c[2]:15.000000
>> Input a[3]:Input b[3]:Input c[3]:24.000000
What you wanted to achieve is quite unclear, and the naming doesn't help, I recommend you to give better names:
struct create doesn't describe what is stored inside
Consider compiling with -Wall -Wextra -Werror.
Your givename() (seems like a bad name) currently only processes one struct as it returns inside the loop. And the way you are calling it after each input of 3 integers it would only process a struct (the first struct each time), and not the array of structs. To process the array of structs you could call it after you got all the input - outside the loop taking input. This shows a version processing during the loop for each struct and then a version processing after the loop with all input.
#include<stdio.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create *storage);
float calculate_totals(struct create storage[3]);
float get_grand_total(struct create [3]);
int main()
{
for(int j = 0; j<3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
float sum = givename(&Create[j]);
printf("%f\n", sum);
}
get_grand_total(Create);
/* calculate all totals after input */
for(int j = 0; j<3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
}
float grand_total = calculate_totals(Create);
printf("grand total = %f\n",grand_total);
}
float givename(struct create *storage)
{
storage->total = storage->a + storage->b + storage->c;
return storage->total;
}
float get_grand_total(struct create storage[3])
{
float grand_total = 0;
for (int i = 0; i < 3; i++)
{
grand_total += storage[i].total;
}
printf("grand total sum=%f\n",grand_total);
return grand_total;
}
float calculate_totals(struct create storage[3])
{
float grand_total = 0;
for(int j = 0; j<3; ++j)
{
storage[j].total = storage[j].a + storage[j].b + storage[j].c;
printf("total for struct %d=%f\n",j+1,storage[j].total);
grand_total += storage[j].total;
}
return grand_total;
}

how can i solve segmentation error in terminal message?

I wrote a simple program to take names and numbers from the user and store it in an array, then compare between each cell until it reach the maximum grade then it displays it. The problem is that when it run it shows a message (segmentation fault (Core dump)). I really don't know what my mistake is.
#include <stdio.h>
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char name[n];
float score[n];
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", & name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %f by student %s", name[index], score[index]);
}
1- you use user input to define the size of an array (wrong)
-- array in c has static size so you must define it's size before the code reach the compiling stage(use dynamic memory allocation instead)
2- scanf("%s", & name[I]); you want to save array of char and save the address at the name variable but name it self not a pointer to save address it's just of char type (wrong)
-- you need pointer to save the address of every name so it's array of pointer and a pointer to allocate the address of the array to it so it's a pointer to poiner and define max size of word if you define size the user input exceed it will produce an error
3- finally you exchanged the %f,%s in printf
#include <stdlib.h>
#include <stdio.h>
#define SIZE_OF_WORD 10
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char **name=(char**)malloc((sizeof(char*)*n));
for (int i = 0; i < n; i++) {
name[i]=(char*)malloc((sizeof(char)*SIZE_OF_WORD));
}
float *score=(float*)malloc((sizeof(float)*n));
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %s by student %.0f\n", name[index],score[index]);
}

Inputting errors in structure pointer code

#include <stdio.h>
typedef struct book
{
int bid;
char bname[50];
} bok;
typedef struct student
{
int roll;
char sec;
char name[50];
bok *issue;
} stud;
int main()
{
int n;
printf("enter no. of students\n");
scanf("%d", &n);
stud s[n];
printf("enter names,section and roll no. of %d students\n", n);
for (int i = 0; i < n; i++)
{
scanf("%s", &s[i].name);
scanf("%c", &s[i].sec);
scanf("%d", &s[i].roll);
}
int m, temp;
printf("enter no. of books\n");
scanf("%d", &m);
bok s1[m];
printf("enter book id and book names of %d books\n", m);
for (int i = 0; i < m; i++)
{
scanf("%d\n", &s1[i].bid);
scanf("%s\n", &s1[i].bname);
}
printf("assign book id to students.\n");
for (int i = 0; i < n; i++)
{
printf("assign id for roll %d\n", s[i].roll);
scanf("%d\n", s[i].issue);
}
int info;
printf("enter roll no. of student to get his/her information and book assigned to him\n ");
scanf("%d\n", &info);
for (int i = 0; i < n; i++)
{
if (s[i].sec == info)
printf("name:%s \nsection:%c \nbook assigned:%s\n", s[i].name, s[i].sec, *s[i].issue);
}
}
my code is not showing any compilation error but it does not give required output.my question is Create 2 two structure array Student and Book by the name S and B. And link the students with their respective books.
Print the books issued by a particular student.
Do not forget the brackets in order to assign user's input to the corresponding struct member:
for (int i = 0; i < n; i++)
{
scanf("%s", &(s[i].name));
scanf("%c", &(s[i].sec));
scanf("%d", &(s[i].roll));
}
and here you need to assign the input to bid, you cannot set an integer for book:
scanf("%d\n", &(s[i]->issue.bid));
or you wil get a segfault.

passing struct array to function for inputting value

Need to pass a struct array to 2 functions so that the user can input the values.
This is the structure needed:
struct Sale {
double quantity;
double unit_p;
char taxable;
};
Calling the function in the main functions as:
no_sales = enter(sales, MAX_SALES);
total(sales, no_sales);
and i am inputting values by:
printf("Quantity : ");
scanf("%lf", &s[i].quantity);
printf("Unit Price : ");
scanf("%lf", &s[i].unit_p);
printf("Taxable(y/n) : ");
scanf("%*c%c%*c", &s[i].taxable);
It compiles fine in gcc compiler. When I ran the program I can enter the values but when I try to print the values it displays all values as 0. The values are not being stored in struct array
output I am getting:
Quantity : 2
Unit Price : 1.99
Taxable(y/n) : y
Quantity Unit Price
0.000000 0.000000
The whole code:
program accepts the values and calculates total price in 2 separate functions
#include <stdio.h>
const int MAX_SALES = 10;
struct Sale {
double quantity;
double unit_p;
char taxable;
};
void total(const struct Sale *s,int n);
int enter(struct Sale *s, int M);
int main()
{
int no_sales;
struct Sale sales[MAX_SALES];
printf("Sale Records \n");
printf("=============\n");
no_sales = enter(sales, MAX_SALES);
total(sales, no_sales);
}
int enter(struct Sale *s, int M)
{
int i = 0;
printf("Quantity : ");
scanf("%lf", &s[i].quantity);
while(s[i].quantity != 0) {
printf("Unit Price : ");
scanf("%lf", &s[i].unit_p);
printf("Taxable(y/n) : ");
scanf("%*c%c%*c", &s[i].taxable);
i++;
if(i == M) {
printf("Maximum exceeded\n");
break;
}
printf("Quantity : ");
scanf("%lf", &s[i].quantity);
}
int j;
for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[i].quantity, s[i].unit_p, s[i].taxable);
}
return i;
}
void total(const struct Sale *s,int n)
{
int i, subtot = 0, hst = 0, tot = 0;
for(i = 0; i < n; i++) {
subtot = subtot + (s[i].quantity * s[i].unit_p);
if(s[i].taxable == 'y' || s[i].taxable == 'Y') {
hst = hst + (0.13 * s[i].quantity * s[i].unit_p);
}
}
tot = subtot + hst;
printf("\n%-12s%.2lf", "Subtotal", subtot);
printf("\n%-12s%.2lf", "HST (13%)", hst);
printf("\n%-12s%.2lf\n", "Total", tot);
}
In function enter() you are using the wrong index variable i to access the struct:
for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[i].quantity, s[i].unit_p, s[i].taxable);
}
which should be
for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[j].quantity, s[j].unit_p, s[j].taxable);
}
Second, in function total(), your variables for calculating the totals, should be of type double
int i;
double subtot = 0, hst = 0, tot = 0;
...

Resources