Why is it not displaying output according record? - c

I want to make cashier program using C language. I use a structure for the record, but when I enter 1 for bar code input, it is not displaying item 1; instead it displays item 2. Here is my code:
#include <stdio.h>
#include <stdlib.h>
struct item
{
char name[10];
int price;
int barcode;
};
struct item detail[10] = {
"item1", 10, 1,
"item2", 20, 2,
"item3", 30, 3,
"item4", 40, 4,
"item1", 50, 5,
"item2", 60, 6,
"item3", 70, 7,
"item4", 80, 8,
"item3", 90, 9,
"item4", 100, 10
};
int main()
{
int ibarcode[10];
int qty[10];
int tot[10];
int j, i, k, grand;
char a;
printf("Program Kasir\n");
for (j = 0; j < 10; j++)
{
printf("ebter barcode : ");
scanf("%d", &ibarcode[j]);
for (i = 0; i < 10; i++)
{
if (ibarcode[j] == detail[i].barcode)
{
printf("item : %s\n", detail[i].name);
printf("price : %d\n", detail[i].price);
printf("enter quantity : ");
scanf("%d", &qty[j]);
tot[j] = detail[j].price * qty[j];
}
if (ibarcode[j] > 10)
{
printf("Barcode isn't valid'\n");
j--;
break;
}
}
printf("\nbuy again? [Y/N] = ");
scanf("%s", &a);
if (a == 'Y' || a == 'y')
{
continue;
} else
{
break;
}
}
grand = 0;
system("cls");
printf("\n name Kasir = Addzifi Moch G\n");
printf(" Tanggal = 03 januari 2017\n");
printf(" Jam = 14:05 WIB\n\n");
printf("+-------------------------------------------------------------------------------------------------+\n");
printf("| Barcode | item \t\t\t| price \t\t| quantity \t| Total |\n");
printf("+-------------------------------------------------------------------------------------------------+\n");
for (k = 0; k <= j; k++)
{
grand += tot[k];
printf("| %d \t | %s\t | %d\t\t | %d\t\t\t| %d |\n", ibarcode[k], detail[k].name, detail[k].price, qty[k], tot[k]);
}
printf("+-------------------------------------------------------------------------------------------------+\n");
printf("|\t\t\t\t\t\t\t Total Yang Harus Dibayarkan = %d |\n", grand);
printf("+-------------------------------------------------------------------------------------------------+\n");
}

The problem is that you're not using the correct index into detail when you print the receipt. You're printing the fields from detail[k], but k isn't the index of the item that the customer purchased, it's just the current iteration of the for() loop.
You need to save the index i that you found when searching detail in the first loop to get the price.
Instead of lots of separate arrays, it would be better to have another struct that contains the purchase details. It can use a pointer to refer to the item in the details array.
struct purchase {
struct item *item;
int qty;
int tot;
} items[10];
Then your first loop would look like:
for (j = 0; j < 10; j++) {
int barcode;
scanf("%d", &barcode);
int item_found = 0;
for (i = 0; i < 10; i++)
{
if (barcode == detail[i].barcode)
{
int qty;
printf("item : %s\n", detail[i].name);
printf("price : %d\n", detail[i].price);
printf("enter quantity : ");
scanf("%d", qty);
items[j].qty = qty;
items[j].tot = qty * deatail[i].price;
items[j].item = &detail[i];
item_found = 1;
break;
}
}
if (!item_found) {
{
printf("Barcode isn't valid'\n");
j--;
break;
}
}
Then you can access the detail info when printing the receipt:
for (k = 0; k <= j; k++)
{
grand += tot[k];
printf("| %d \t | %s\t | %d\t\t | %d\t\t\t| %d |\n", item[k].item->barcode, item[k].item->name, item[k].item->price, item[k].qty, item[k].tot);
}

In C/C++ indexing starts from 0 not 1.
ibarcode[10] means that there are indexes from 0 to 9.

Related

How can I display all of the elements stored in the array?

How can I display all of the elements stored in the array? I just only want to display all the inputted elements.
This is my code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct studinfo{
char remarks, name[100];
float first, second, finalave;
};
int main()
{
struct studinfo stud;
int i, n;
char temp;
printf("Enter Number of Student/s to be Stored: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("\nEnter Student Name: ");
scanf("%c", &temp);
scanf("%[^\n]", stud.name);
printf("Enter 1st Sem Average: ");
scanf("%f", &stud.first);
printf("Enter 2nd Sem Average: ");
scanf("%f", &stud.second);
stud.finalave = (stud.first + stud.second) /2 ;
printf("\nThe Final Average: %f", stud.finalave);
printf("\n");
}
for (i = 0; i < n; i++)
{
if (stud.finalave > 1.0 && stud.finalave <= 1.25 )
{
stud.remarks = 'S';
}
else if (stud.finalave > 1.5 && stud.finalave <= 1.75)
{
stud.remarks = 'A';
}
else if (stud.finalave > 2.0 && stud.finalave <= 2.5)
{
stud.remarks = 'B';
}
else if (stud.finalave > 2.75 && stud.finalave <= 3.0)
{
stud.remarks = 'C';
}
else if (stud.finalave >= 3.00)
{
stud.remarks = 'F';
}
}
This is where the error in displaying:
printf("\n");
printf("Name\t\tAverage\t\tRemarks\t\tScholarship");
for (i = 0; i < n; i++)
{
printf("\n%s\t%f\t%c", stud.name, stud.finalave, stud.remarks);
}
}
My expected output for this code is that all the inputted elements will be displayed but it turns out that only the last inputted are detected. What should I do?
First, define an array of structures like struct studinfo stud[n] in replace of 'n' you can use any variable. Then when taking the input use stud[i].name here i represents the index of the array.
And for displaying you can use stud[i].name similar to getting input.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct studinfo{
char remarks, name[100];
float first, second, finalave;
};
int main()
{
int i, n;
char temp;
printf("Enter Number of Student/s to be Stored: ");
scanf("%d", &n);
struct studinfo stud[n];
for (i = 0; i < n; i++)
{
printf("\nEnter Student Name: ");
scanf("%c", &temp);
scanf("%[^\n]", stud[i].name);
printf("Enter 1st Sem Average: ");
scanf("%f", &stud[i].first);
printf("Enter 2nd Sem Average: ");
scanf("%f", &stud[i].second);
stud[i].finalave = (stud[i].first + stud[i].second) /2 ;
printf("\nThe Final Average: %f", stud[i].finalave);
printf("\n");
}
for (i = 0; i < n; i++)
{
if (stud[i].finalave > 1.0 && stud[i].finalave <= 1.25 )
{
stud[i].remarks = 'S';
}
else if (stud[i].finalave > 1.5 && stud[i].finalave <= 1.75)
{
stud[i].remarks = 'A';
}
else if (stud[i].finalave > 2.0 && stud[i].finalave <= 2.5)
{
stud[i].remarks = 'B';
}
else if (stud[i].finalave > 2.75 && stud[i].finalave <= 3.0)
{
stud[i].remarks = 'C';
}
else if (stud[i].finalave >= 3.00)
{
stud[i].remarks = 'F';
}
}
printf("\n");
printf("Name\t\tAverage\t\tRemarks\t\tScholarship");
for (i = 0; i < n; i++)
{
printf("\n%s\t%f\t%c", stud[i].name, stud[i].finalave, stud[i].remarks);
}
}

Average score facing some technical issues

I have followed everything in the book, yet my average score fails me, every single time. I have debugged my program multiple times, in vain.
My minimal executable code:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX_TESTS 5
#define MAXQUESTION 10000
bool myread(const char * format, void * address) {
char buffer[1024];
fgets(buffer, sizeof buffer, stdin);
return sscanf(buffer, format, address) == 1;
}
struct struc {
int a;
int b;
int c;
int add;
int grade;
};
int sj(int n) {
int t;
t = rand() % n;
return t;
}
void ctm_i(struct struc * t) {
{
t -> a = sj(101);
t -> c = sj(4);
if (t -> c == 1) {
t -> b = sj(101 - (t -> a));
t -> add = (t -> a) + (t -> b);
} else {
t -> b = sj((t -> a) + 1);
t -> add = (t -> a) - (t -> b);
}
t -> grade = 0;
}
}
void tcm_i(struct struc * t, int n) {
int ad;
printf(" ***********************************************************************"
"*********\n");
printf(" ......................................................................."
".........\n");
printf(" Question %d\n\n", n + 1);
printf(" You have 3 attempts for this question\n\n");
if (t -> c == 1)
printf(" %d+%d= ", t -> a, t -> b);
else
printf(" %d-%d= ", t -> a, t -> b);
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 10;
printf(" You earned 10 marks\n\n");
} else {
printf("\n Incorrect, you have 2 attempts remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 7;
printf(" You earned 7 marks\n\n");
} else {
printf("\n Incorrect, you have 1 attempt remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 5;
printf(" You earned 5 marks\n\n");
} else {
t -> grade = 0;
printf("\n Failure, 0 mark\n\n");
printf("\n The correct answer is %d\n\n", t -> add);
}
}
}
printf(" ......................................................................."
".........\n");
printf(" ***********************************************************************"
"*********\n");
}
void quiz(char name[]) {
int rounds = 0;
int highest = 0;
int lowest = INT_MAX;
float allScore = 0;
float avg = 0.0;
int i, j, g = 0;
struct struc test[MAX_TESTS];
srand((unsigned) time(NULL));
for (;;) {
rounds++;
for (i = 0; i < MAX_TESTS; i++) // generate all questions
{
ctm_i( & test[i]);
for (j = 0; j < i; j++)
if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
//if question is already present
ctm_i( & test[i]); //then re-generate
}
printf("\n Are you ready? Press Enter key to continue. ");
myread("", NULL);
for (i = 1; i <= 5; i++) {
printf(" *******************************************************************"
"**"
"***********\n");
printf(" ..................................................................."
".."
"...........\n");
}
// Take quiz
for (i = 0; i < MAX_TESTS; i++)
tcm_i( & test[i], i);
printf(" End\n\n");
bool done = false;
bool unsure = true;
bool showS = true;
while (unsure) {
unsure = false;
puts("\n");
if (showS) {
puts(" Enter 'S' to show results");
}
puts(" Enter 'P' to play another round");
puts(" Enter 'R' to return to main menu");
char choice;
printf(" ");
myread(" %c", & choice);
printf("\n");
if (choice == 'r' || choice == 'R') {
done = true;
} else {
///////////////////////// Changes /////////////
g = 0;
// calculate total score for current round
for (i = 0; i < MAX_TESTS; i++) {
g += test[i].grade; //add score of each question
}
allScore += g; //add current round's score to total
avg = allScore / rounds; //average of all rounds
if (g > highest) {
highest = g;
}
if (g < lowest) {
lowest = g;
}
if (choice == 'S' || choice == 's') {
showS = false;
if (rounds == 1) {
printf(" Final score: %d/100\n", g); //display round score
printf(" ****** Player: %s ******\n", name);
} else {
printf(" Round %d score: %d/100\n", rounds, g); //display round score
printf(" Highest score: %d/100\n", highest);
printf(" Lowest score : %d/100\n", lowest);
printf(" Average score: %f/100\n", avg);
printf(" ****** Player: %s ******\n", name);
}
unsure = true;
} else if (choice == 'P' || choice == 'p') {
/// nothing to be done here
//we will display next test
} else {
puts(" Invalid input!");
unsure = true;
}
////////////////////////////////////
}
}
if (done)
break;
}
}
int main() {
char i1 = '1';
char name[25]; // ig;
printf("\n Welcome");
printf("\n");
while (i1 != 0) {
printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz *\n");
printf(" * 2.Quit *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
printf("\n Enter Quiz:\n");
quiz(name); // calling quiz function defined in file "maincode.c"
break;
case '2':
printf(" Quit.\n\n");
}
}
return 0;
}
Hope that fulfilled the definition of an MRE.
So I have snipped off some bombastic lines, and the ones left are the important ones, I think.
The problem is in your function quiz, and in particular in the while (unsure) loop. In this loop, you add the most recent score to the running total:
allScore += g; //add current round's score to total
This should happen once per round played. But if the user inputs "S" or something invalid, your program sets
unsure = true;
which means the loop will run again, before the next round is played. It then adds the most recent score a second time to the grand total.
The most logical solution would be to move all the calculations of totals, maximum, minimum, average out of the while-loop. The loop serves a different purpose: it is for user interaction and reporting, not for processing results.
possible chance of multiple avg calculation for same round again. Keep flag to track accounting of score, so we will not do the same more than once till the game is not played again.
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX_TESTS 5
#define MAXQUESTION 10000
bool myread(const char * format, void * address) {
char buffer[1024];
fgets(buffer, sizeof buffer, stdin);
return sscanf(buffer, format, address) == 1;
}
struct struc {
int a;
int b;
int c;
int add;
int grade;
};
int sj(int n) {
int t;
t = rand() % n;
return t;
}
void ctm_i(struct struc * t) {
{
t -> a = sj(101);
t -> c = sj(4);
if (t -> c == 1) {
t -> b = sj(101 - (t -> a));
t -> add = (t -> a) + (t -> b);
} else {
t -> b = sj((t -> a) + 1);
t -> add = (t -> a) - (t -> b);
}
t -> grade = 0;
}
}
void tcm_i(struct struc * t, int n) {
int ad;
printf(" ***********************************************************************"
"*********\n");
printf(" ......................................................................."
".........\n");
printf(" Question %d\n\n", n + 1);
printf(" You have 3 attempts for this question\n\n");
if (t -> c == 1)
printf(" %d+%d= ", t -> a, t -> b);
else
printf(" %d-%d= ", t -> a, t -> b);
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 10;
printf(" You earned 10 marks\n\n");
} else {
printf("\n Incorrect, you have 2 attempts remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 7;
printf(" You earned 7 marks\n\n");
} else {
printf("\n Incorrect, you have 1 attempt remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 5;
printf(" You earned 5 marks\n\n");
} else {
t -> grade = 0;
printf("\n Failure, 0 mark\n\n");
printf("\n The correct answer is %d\n\n", t -> add);
}
}
}
printf(" ......................................................................."
".........\n");
printf(" ***********************************************************************"
"*********\n");
}
void quiz(char name[]) {
int rounds = 0;
int highest = 0;
int lowest = INT_MAX;
float allScore = 0;
float avg = 0.0;
int i, j, g = 0;
struct struc test[MAX_TESTS];
srand((unsigned) time(NULL));
for (;;) {
rounds++;
for (i = 0; i < MAX_TESTS; i++) // generate all questions
{
ctm_i( & test[i]);
for (j = 0; j < i; j++)
if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
//if question is already present
ctm_i( & test[i]); //then re-generate
}
printf("\n Are you ready? Press Enter key to continue. ");
myread("", NULL);
for (i = 1; i <= 5; i++) {
printf(" *******************************************************************"
"**"
"***********\n");
printf(" ..................................................................."
".."
"...........\n");
}
// Take quiz
for (i = 0; i < MAX_TESTS; i++)
tcm_i( & test[i], i);
printf(" End\n\n");
bool done = false;
bool unsure = true;
bool showS = true;
bool acct = false;
while (unsure) {
unsure = false;
puts("\n");
if (showS) {
puts(" Enter 'S' to show results");
}
puts(" Enter 'P' to play another round");
puts(" Enter 'R' to return to main menu");
char choice;
printf(" ");
myread(" %c", & choice);
printf("\n");
if (choice == 'r' || choice == 'R') {
done = true;
} else {
///////////////////////// Changes /////////////
if (false == acct) {
g = 0;
// calculate total score for current round
for (i = 0; i < MAX_TESTS; i++) {
g += test[i].grade; //add score of each question
}
allScore += g; //add current round's score to total
avg = allScore / rounds; //average of all rounds
if (g > highest) {
highest = g;
}
if (g < lowest) {
lowest = g;
}
acct = true;
}
if (showS &&(choice == 'S' || choice == 's')) {
showS = false;
if (rounds == 1) {
printf(" Final score: %d/100\n", g); //display round score
printf(" ****** Player: %s ******\n", name);
} else {
printf(" Round %d score: %d/100\n", rounds, g); //display round score
printf(" Highest score: %d/100\n", highest);
printf(" Lowest score : %d/100\n", lowest);
printf(" Average score: %f/100\n", avg);
printf(" ****** Player: %s ******\n", name);
}
unsure = true;
} else if (choice == 'P' || choice == 'p') {
/// nothing to be done here
//we will display next test
} else {
puts(" Invalid input!");
unsure = true;
}
////////////////////////////////////
}
}
if (done)
break;
}
}
int main() {
char i1 = '1';
char name[25]; // ig;
printf("\n Welcome");
printf("\n");
while (i1 != 0) {
printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz *\n");
printf(" * 2.Quit *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
printf("\n Enter Quiz:\n");
quiz(name); // calling quiz function defined in file "maincode.c"
break;
case '2':
printf(" Quit.\n\n");
}
}
return 0;
}
Output:
Enter 'S' to show results
Enter 'P' to play another round
Enter 'R' to return to main menu
s
Round 2 score: 47/100
Highest score: 50/100
Lowest score : 47/100
Average score: 48.500000/100
****** Player: ******

Team and Fight Randomizer in C

I'm trying to make a program, which puts a given amount of players in a given amount of teams. Afterwards they should be randomly chosen (eg. you roll the "dice" and Team 3's Player 42 and shall fight against Team 4's Player 22 (All the players are randomly put in the different teams, which are limited to the choice of the Gamemaster)).
In my code I have the basic output and structure. It says something like:
Team 1 now owns Player 43
Team 2 now owns Player 12
Team 4 now owns Player 1
Team 3 now owns Player 54
But my question is, how - based on the code - I could save this information and how can I (afterwards) let the players randomly fight? Members of the same team should NOT be able to fight each other and after each fight I want the players to be somehow on a "blacklist" where they can't be rolled anymore.
My code so far
#include <stdio.h>
#include <stdlib.h>
int main()
{
int mitglieder, teams, teameins = 0, teamzwei = 0, teamdrei = 0, teamvier = 0;
printf("Teamcreation\n");
printf("\nNumber of Players: ");
scanf("%d", &mitglieder);
printf("\nNumber of Teams: ");
scanf("%d", &teams);
printf("\nThere are ");
printf("%d", mitglieder);
printf(" Player in ");
printf("%d", teams);
printf(" Teams. \n");
int array[mitglieder];
for (int i = 0; i < mitglieder; i++)
{ // fill array
array[i] = i;
}
printf("The Player are in the following Teams: \n ");
for (int i = 0; i < mitglieder; i++)
{ // shuffle array
int temp = array[i];
int randomIndex = rand() % mitglieder;
array[i] = array[randomIndex];
array[randomIndex] = temp;
}
for (int i = 0; i < mitglieder; i++)
{ // print array
int random_number = rand() % teams + 1;
int tp = random_number;
if(tp == 1)
{
teameins+1;
}
else if(tp == 2)
{
teamzwei+1;
}
else if(tp == 3)
{
teamdrei+1;
}
else if(tp == 4)
{
teamvier+1;
}
printf("Team %d - Spieler: %d\n ",random_number,array[i] + 1);
}
if( (teamvier == 0) && (teamdrei == 0) )
{
printf("\n%d Mitglieder in Team 1 und %d Mitglieder in Team2",teameins,teamzwei);
}
else if((teamvier == 0) && (teamdrei < 0))
{
printf("\n%d Mitglieder in Team 1, %d Mitglieder in Team2 und %d Mitglieder in Team3.",teameins,teamzwei,teamdrei);
}
else if(teamvier < 0)
{
printf("\n%d Mitglieder in Team 1, %d Mitglieder in Team2, %d Mitglieder in Team 3 und %d Mitglieder in Team4.",teameins,teamzwei,teamdrei,teamvier);
}
return 0;
}
Before basing something on the given code, you should correct the errors in it, which are within the counting of team members and the printing of the counts. While you're at it, you could make it work also for more than four teams, e. g.:
#include <string.h>
…
int Spielerteam[mitglieder]; // team of the player
int Teamstaerke[teams]; // team member counts
memset(Teamstaerke, 0, sizeof Teamstaerke); // zero the counts
for (int i = 0; i < mitglieder; i++)
{ // print array
int random_number = rand() % teams;
int tp = random_number + 1;
Spielerteam[i] = tp; // save player's team information
Teamstaerke[random_number]++; // count the member
printf("Team %d - Spieler: %d\n ", tp, array[i] + 1);
}
for (int i = 0; i < teams; i++)
printf("%s%d Mitglieder in Team %d",
i ? i+1 == teams ? " und " : ", " : "\n", Teamstaerke[i], i+1);
puts("");
After that, the team each player array[i] + 1 belongs to is saved in Spielerteam[i].

please help really stuck on structures

hi guys been using this site for a while now for tips but never posted before (first time for everything i suppose) anyway doing an assignment for college (Manufacturing degree) so probably basic to some of you. basically
the problem is in the search by student name void near the bottom the program runs but crashes as soon as i enter the name any help would be really appreciated
#include <stdlib.h>
#include <stdio.h>
#define SIZE 2
struct Student
{
long StudentID;//works
char fname[21];//works
char sname[21];//does not work
int year;//works
char course[51];//works
float results_semester_1[6];//works
float results_semester_2[6];//works
int free; // 1 means its free, 0 means its not
};
struct Student BENG[SIZE];
int menu(); // function prototype
void add_student(); // function prototype
void display_students(); // function prototype
void display_results(); // function prototype
void search_for_student_studentID(); // function prototype
void search_for_student_by_name(); // function prototype
void delete_student(); // function prototype
void initialise_database(); // function prototype
void Run_statistics_for_individual_student(); // function prototype
void Run_statistics_for_all_student(); // function prototype
int linear_search(long); // function prototype
int linear_search_sname(char); // function prototype
int main()
{
initialise_database(); // call the function to set all free positions to 1
for(;;) // infinite loop
{
switch(menu()) // calling function menu within switch
{
case 1:
add_student(); // calling function add_student
break;
case 2:
delete_student(); // calling function delete_student
break;
case 3:
display_students(); // calling function display_students
break;
case 4:
search_for_student_studentID(); // calling function display_students
break;
case 5:
search_for_student_by_name(); // calling function display_students
break;
case 6:
Run_statistics_for_individual_student(); // calling function display_students
break;
case 7:
Run_statistics_for_all_student(); // calling function display_students
break;
case 8:
display_results(); // calling function display_students
break;
case 9:
printf("Quitting Program\n");
exit(1);
default:
printf("Invalid option chosen\n\n");
}
} // end of infinite loop
return 0;
}
void add_student()
{
int freepos = -1, i, j,k,year;
for(i = 0; i < SIZE; i++)
{
if(BENG[i].free == 1)
{
freepos = i;
break;
}
}
if(freepos != -1)
{
do
{
printf("Enter student ID:\n");
scanf("%ld", &BENG[freepos].StudentID);
}
while(BENG[freepos].StudentID<10000000 ||BENG[freepos].StudentID>99999999);
printf("Enter firstname:\n");
scanf("%s", BENG[freepos].fname);
printf("Enter surname:\n");
scanf("%s", BENG[freepos].sname);
do
{
printf("Enter year of course:\n");
scanf("%d", &BENG[freepos].year);
}
while(BENG[freepos].year < 1 || BENG[freepos].year > 4);
printf("Enter course name:\n");
scanf("%s", BENG[freepos].course);
for(j = 0; j < 6; j++)
{
printf("Enter result of semester 1 Module %d:\n", j+1);
scanf("%f", &BENG[freepos].results_semester_1[j]);
}
for(k = 0; k < 6; k++)
{
printf("Enter result of semester 2 Module %d:\n", k+1);
scanf("%f", &BENG[freepos].results_semester_2[k]);
}
BENG[freepos].free = 0; // mark record as taken
}
else
printf("No position free at present\n");
}
void display_students()
{
// output the values just entered
int i, j;
for(i = 0; i < SIZE; i++)
{
if(BENG[i].free == 0) // only print taken records
{
printf("Student ID: %ld:\n", BENG[i].StudentID);
printf("Firstname: %s\n", BENG[i].fname);
printf("Surname: %s\n", BENG[i].sname);
printf("Year: %d\n", BENG[i].year);
printf("Course: %s\n", BENG[i].course);
for(j = 0; j < 6; j++)
{
printf("Result semester 1 Module %d: %0.2f\n", j+1, BENG[i].results_semester_1[j]);
} // end of for
for(j = 0; j < 6; j++)
{
printf("Result semester 2 Module %d: %0.2f\n", j+1, BENG[i].results_semester_2[j]);
} // end of for
} // end of if
} // end of for
}
void display_results()
{
// output the values just entered
int i, j;
for(i = 0; i < SIZE; i++)
{
if(BENG[i].free == 0) // only print taken records
{
for(j = 0; j < 6; j++)
{
printf("Result semester 1 Module %d: %0.2f\n", j+1, BENG[i].results_semester_1[j]);
} // end of for
for(j = 0; j < 6; j++)
{
printf("Result semester 2 Module %d: %0.2f\n", j+1, BENG[i].results_semester_2[j]);
} // end of for
} // end of if
} // end of for
}
int menu()
{
int choice;
printf("1. To add a student\n");
printf("2. To delete a student\n");
printf("3. To display all students\n");
printf("4. Find a student using studentID\n");
printf("5. Find a student by student Surname\n");
printf("6. Find student would you like to run statistics for\n");
printf("7. Find statistics for all students\n");
printf("8. Display results of all students\n");
printf("9. Exit Program\n");
do
{
scanf("%d", &choice);
}
while(choice < 1 || choice > 9);
return choice;
}
void initialise_database()
{
int i;
for(i = 0; i < SIZE; i++) // set all structure variables free to 1
BENG[i].free = 1;
}
void delete_student()
{
long search;
int position,freepos;
printf("Enter the number of student to delete\n");
scanf("%ld",&search);
position = linear_search(search);
if ( position == -1 )
printf("%d is not present in array.\n", search);
else
printf("%d is present at location %d.\n", search, position+1);
BENG[position].free = 1;
return;
}
void search_for_student_studentID()
{
long search;
int position,j,i;
printf("Enter the number to search\n");
scanf("%ld",&search);
position = linear_search(search);
if ( position == -1 )
printf("%d is not present in array.\n", search);
else
printf("%d is present at location %d.\n", search, position+1);
printf("Student ID: %ld:\n", BENG[position].StudentID);
printf("Firstname: %s\n", BENG[position].fname);
printf("Surname: %s\n", BENG[position].sname);
printf("Year: %d\n", BENG[position].year);
printf("Course: %s\n", BENG[position].course);
for(j = 0; j < 6; j++)
{
printf("Result semester 1 Module %d: %0.2f\n", j+1, BENG[i].results_semester_1[j]);
}
for(j = 0; j < 6; j++)
{
printf("Result semester 2 Module %d: %0.2f\n", j+1, BENG[i].results_semester_2[j]);
}
return;
}
void search_for_student_by_name(sname)
{
int position,j,i;
printf("Enter the surname of student to search\n");
scanf("%s",&sname);
position = linear_search_sname(sname);
if ( position == 1 )
printf("%s is not present in array.\n", sname);
else
printf("%s is present at location %d.\n", sname, position+1);
printf("Student ID: %ld:\n", BENG[position].StudentID);
printf("Firstname: %s\n", BENG[position].fname);
printf("Surname: %s\n", BENG[position].sname);
printf("Year: %d\n", BENG[position].year);
printf("Course: %s\n", BENG[position].course);
for(j = 0; j < 6; j++)
{
printf("Result semester 1 Module %d: %0.2f\n", j+1, BENG[i].results_semester_1[j]);
}
for(j = 0; j < 6; j++)
{
printf("Result semester 2 Module %d: %0.2f\n", j+1, BENG[i].results_semester_2[j]);
}
return;
}
int linear_search(long find)
{
int c;
for ( c = 0 ; c < SIZE ; c++ )
{
if (BENG[c].StudentID == find )
{
return c;
break;
}
}
return -1;
}
int linear_search_sname(char find)
{
int c;
for ( c = 0 ; c < SIZE ; c++ )
{
if (BENG[c].sname[21] == find )
{
return c;
break;
}
}
return -1;
}
void Run_statistics_for_individual_student()
{
long search;
int position,j,i,k,r,max,minsums,min=100;
float sums = 0,maxsums=0;
printf("Enter the number to search\n");
scanf("%ld",&search);
printf("The statistics for student ID:\n",search);
position = linear_search(search);
if ( position == -1 )
printf("%d is not present in array.\n", search);
else
for(i = 0; i < 6; i++)
{
sums += BENG[position].results_semester_1[i];
}
printf("Average grade over 6 subjects for this student in semester 1 is %0.2f marks\n", sums/6);
for(i = 0; i < 6; i++)
{
maxsums = BENG[position].results_semester_1[i];
}
if(maxsums>max)
{
max=maxsums;
} // end of if
printf("Max grade for this student in semester 1 is %d\n", max);
{
for(k = 0; k < 6; k++)
{
if(BENG[position].results_semester_1[k]<min)
{
min=BENG[position].results_semester_1[k];
} // end of if
}// end of for
printf("Min grade for this student in semester 2 is %d\n", min);
}
for(i = 0; i < 6; i++)
{
sums += BENG[position].results_semester_2[i];
}
printf("Average grade over 6 subjects for this student in semester 2 is %0.2f marks\n", sums/6);
for(i = 0; i < 6; i++)
{
maxsums = BENG[position].results_semester_2[i];
}
if(maxsums>max)
{
max=maxsums;
} // end of if
printf("Max grade for this student in semester 2 is %d\n", max);
{
for(k = 0; k < 6; k++)
{
if(BENG[position].results_semester_2[k]<min)
{
min=BENG[position].results_semester_2[k];
} // end of if
}// end of for
printf("Min grade for this student in semester 2 is %d\n", min);
}
return ;
}
void Run_statistics_for_all_student()
{
// output the values just entered
int i,j,k, max,min=100;
float sums,maxsums=0;
{
for(i = 0; i < SIZE; i++)
if(BENG[i].free == 0) // only print taken records
{
for(j = 0; j < 6; j++)
{
for(i = 0; i < SIZE; i++)
{
sums += BENG[i].results_semester_1[i];
} // end of for
} // end of for
} // end of if
printf("Average grade for all students in semester 1 is %0.2f \n", sums/(SIZE*6));
}
{
for(k = 0; k < SIZE; k++)
if(BENG[i].free == 0) // only print taken records
{
for(j = 0; j < 6; j++)
{
for(i = 0; i < SIZE; i++)
{
maxsums = BENG[i].results_semester_1[i];
}
if(maxsums>max)
{
max=maxsums;
}
}// end of for
}// end of if
}
printf("Max grade for all student in semester 1 is%d\n", max);
{
for(k = 0; k < SIZE; k++)
if(BENG[k].free == 0) // only print taken records
{
for(j = 0; j < 6; j++)
{
for(i = 0; i < 6; i++)
{
if(BENG[i].results_semester_1[i]<min)
{
min=BENG[i].results_semester_1[i];
}
}// end of for
}// end of for
}// end of if
}
printf("Min grade for all student in semester 1 is %d\n", min);
return ;
}
There are a large number of errors throughout your code. All of them due to NOT SLOWING DOWN AND THINKING ABOUT EACH LINE (and part of each line). C is an exact language. That is one of its strengths. There is no such thing as close enough in either syntax or logic. One way to find most of these ...oversights... is to compile with warnings turned on. A compile string for your program should at a minimum contain -Wall -Wextra. For example:
gcc -Wall -Wextra -o student_database student_database.c
That will catch most of your basic syntax and variable type mismatch problems. Eliminate each and every warning. The compiler didn't accidentally throw them. They mean something.
That being said, I have eliminated the warnings in your code. I have been through the add_student function to the extent that it will accept input and prevent newlines from remaining in the input buffer prior to the next entry. I have corrected other areas just to the extent to resolve the compiler warnings. Your code still needs lots of work. This will give you a good start and eliminate that overwhelmed feeling (for the time being). Work through your code, look at the corrections I've made. Slow down -- and you will do fine.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 4
struct Student
{
long StudentID;//works
char fname[21];//works
char sname[21];//does not work
int year;//works
char course[51];//works
float results_semester_1[6];//works
float results_semester_2[6];//works
int free; // 1 means its free, 0 means its not
};
struct Student BENG[SIZE];
int menu(); // function prototype
void add_student(); // function prototype
void display_students(); // function prototype
void display_results(); // function prototype
void search_for_student_studentID(); // function prototype
void search_for_student_by_name(); // function prototype
void delete_student(); // function prototype
void initialise_database(); // function prototype
void Run_statistics_for_individual_student(); // function prototype
void Run_statistics_for_all_student(); // function prototype
int linear_search(long); // function prototype
int linear_search_sname(char*); // function prototype
int main()
{
initialise_database(); // call the function to set all free positions to 1
for(;;) // infinite loop
{
switch(menu()) // calling function menu within switch
{
case 1:
add_student(); // calling function add_student
break;
case 2:
delete_student(); // calling function delete_student
break;
case 3:
display_students(); // calling function display_students
break;
case 4:
search_for_student_studentID(); // calling function display_students
break;
case 5:
search_for_student_by_name(); // calling function display_students
break;
case 6:
Run_statistics_for_individual_student(); // calling function display_students
break;
case 7:
Run_statistics_for_all_student(); // calling function display_students
break;
case 8:
display_results(); // calling function display_students
break;
case 9:
printf("Quitting Program\n");
exit(1);
default:
printf("Invalid option chosen\n\n");
}
} // end of infinite loop
return 0;
}
void add_student()
{
int freepos = -1;
int i = 0;
int j = 0;
int k = 0;
for(i = 0; i < SIZE; i++)
{
if(BENG[i].free == 1)
{
freepos = i;
break;
}
}
if(freepos != -1)
{
do
{
printf("Enter student ID (8-digits): ");
scanf("%ld%*c", &BENG[freepos].StudentID);
}
while(BENG[freepos].StudentID<10000000 || BENG[freepos].StudentID>99999999);
printf("Enter firstname: ");
scanf("%[^\n]%*c", BENG[freepos].fname);
printf("Enter surname: ");
scanf("%[^\n]%*c", BENG[freepos].sname);
do
{
printf("Enter year of course (1-4): ");
scanf("%d%*c", &BENG[freepos].year);
}
while(BENG[freepos].year < 1 || BENG[freepos].year > 4);
printf("Enter course name: ");
scanf("%[^\n]%*c", BENG[freepos].course);
for(j = 0; j < 6; j++)
{
printf("Enter result of semester 1 Module %d: ", j+1);
scanf("%f%*c", &BENG[freepos].results_semester_1[j]);
}
for(k = 0; k < 6; k++)
{
printf("Enter result of semester 2 Module %d: ", k+1);
scanf("%f%*c", &BENG[freepos].results_semester_2[k]);
}
BENG[freepos].free = 0; // mark record as taken
}
else
printf("No position free at present\n");
}
void display_students()
{
// output the values just entered
int i, j;
for(i = 0; i < SIZE; i++)
{
if(BENG[i].free == 0) // only print taken records
{
printf("Student ID: %ld:\n", BENG[i].StudentID);
printf("Firstname: %s\n", BENG[i].fname);
printf("Surname: %s\n", BENG[i].sname);
printf("Year: %d\n", BENG[i].year);
printf("Course: %s\n", BENG[i].course);
for(j = 0; j < 6; j++)
{
printf("Result semester 1 Module %d: %0.2f\n", j+1, BENG[i].results_semester_1[j]);
} // end of for
for(j = 0; j < 6; j++)
{
printf("Result semester 2 Module %d: %0.2f\n", j+1, BENG[i].results_semester_2[j]);
} // end of for
} // end of if
} // end of for
}
void display_results()
{
// output the values just entered
int i, j;
for(i = 0; i < SIZE; i++)
{
if(BENG[i].free == 0) // only print taken records
{
for(j = 0; j < 6; j++)
{
printf("Result semester 1 Module %d: %0.2f\n", j+1, BENG[i].results_semester_1[j]);
} // end of for
for(j = 0; j < 6; j++)
{
printf("Result semester 2 Module %d: %0.2f\n", j+1, BENG[i].results_semester_2[j]);
} // end of for
} // end of if
} // end of for
}
int menu()
{
int choice;
printf("1. To add a student\n");
printf("2. To delete a student\n");
printf("3. To display all students\n");
printf("4. Find a student using studentID\n");
printf("5. Find a student by student Surname\n");
printf("6. Find student would you like to run statistics for\n");
printf("7. Find statistics for all students\n");
printf("8. Display results of all students\n");
printf("9. Exit Program\n");
do
{
scanf("%d", &choice);
}
while(choice < 1 || choice > 9);
return choice;
}
void initialise_database()
{
int i;
for(i = 0; i < SIZE; i++) // set all structure variables free to 1
BENG[i].free = 1;
}
void delete_student()
{
long search = 0;
int position = 0;
printf("Enter the number of student to delete\n");
scanf("%ld%*c",&search);
position = linear_search(search);
if ( position == -1 )
printf("%ld is not present in array.\n", search);
else
printf("%ld is present at location %d.\n", search, position+1);
BENG[position].free = 1;
return;
}
void search_for_student_studentID()
{
long search = 0;
int position = 0;
int j = 0;
printf ("Enter the number to search: ");
scanf ("%ld%*c",&search);
position = linear_search (search);
if ( position == -1 )
printf("%ld is not present in array.\n", search);
else
printf("%ld is present at location %d.\n", search, position+1);
printf("Student ID: %ld:\n", BENG[position].StudentID);
printf("Firstname: %s\n", BENG[position].fname);
printf("Surname: %s\n", BENG[position].sname);
printf("Year: %d\n", BENG[position].year);
printf("Course: %s\n", BENG[position].course);
for(j = 0; j < 6; j++)
{
printf("Result semester 1 Module %d: %0.2f\n", j+1, BENG[position].results_semester_1[j]);
}
for(j = 0; j < 6; j++)
{
printf("Result semester 2 Module %d: %0.2f\n", j+1, BENG[position].results_semester_2[j]);
}
return;
}
void search_for_student_by_name (char *sname)
{
int position = 0;
int j = 0;
printf("Enter the surname of student to search\n");
scanf("%[^\n]%*c", sname);
position = linear_search_sname(sname);
if ( position == 1 )
printf("%s is not present in array.\n", sname);
else
printf("%s is present at location %d.\n", sname, position+1);
printf("Student ID: %ld:\n", BENG[position].StudentID);
printf("Firstname: %s\n", BENG[position].fname);
printf("Surname: %s\n", BENG[position].sname);
printf("Year: %d\n", BENG[position].year);
printf("Course: %s\n", BENG[position].course);
for(j = 0; j < 6; j++)
{
printf("Result semester 1 Module %d: %0.2f\n", j+1, BENG[position].results_semester_1[j]);
}
for(j = 0; j < 6; j++)
{
printf("Result semester 2 Module %d: %0.2f\n", j+1, BENG[position].results_semester_2[j]);
}
return;
}
int linear_search(long find)
{
int c = 0;
for ( c = 0 ; c < SIZE ; c++ )
if (BENG[c].StudentID == find )
return c;
return -1;
}
int linear_search_sname(char *find)
{
int c = 0;
for ( c = 0 ; c < SIZE ; c++ )
if (strcmp (BENG[c].sname, find) == 0 )
return c;
return -1;
}
void Run_statistics_for_individual_student()
{
long search = 0;
int position = 0;
int i = 0;
int k = 0;
int max = 0;
int min = 100;
float sums = 0,maxsums=0;
printf("Enter the number to search\n");
scanf("%ld",&search);
printf("The statistics for student ID (%ld):\n",search);
position = linear_search(search);
if ( position == -1 )
printf("%ld is not present in array.\n", search);
else
for(i = 0; i < 6; i++)
{
sums += BENG[position].results_semester_1[i];
}
printf("Average grade over 6 subjects for this student in semester 1 is %0.2f marks\n", sums/6);
for(i = 0; i < 6; i++)
{
maxsums = BENG[position].results_semester_1[i];
}
if(maxsums>max)
{
max=maxsums;
} // end of if
printf("Max grade for this student in semester 1 is %d\n", max);
{
for(k = 0; k < 6; k++)
{
if(BENG[position].results_semester_1[k]<min)
{
min=BENG[position].results_semester_1[k];
} // end of if
}// end of for
printf("Min grade for this student in semester 2 is %d\n", min);
}
for(i = 0; i < 6; i++)
{
sums += BENG[position].results_semester_2[i];
}
printf("Average grade over 6 subjects for this student in semester 2 is %0.2f marks\n", sums/6);
for(i = 0; i < 6; i++)
{
maxsums = BENG[position].results_semester_2[i];
}
if(maxsums>max)
{
max=maxsums;
} // end of if
printf("Max grade for this student in semester 2 is %d\n", max);
{
for(k = 0; k < 6; k++)
{
if(BENG[position].results_semester_2[k]<min)
{
min=BENG[position].results_semester_2[k];
} // end of if
}// end of for
printf("Min grade for this student in semester 2 is %d\n", min);
}
return ;
}
void Run_statistics_for_all_student()
{
// output the values just entered
int i,j,k, max,min=100;
float sums,maxsums=0;
{
for(i = 0; i < SIZE; i++)
if(BENG[i].free == 0) // only print taken records
{
for(j = 0; j < 6; j++)
{
for(i = 0; i < SIZE; i++)
{
sums += BENG[i].results_semester_1[i];
} // end of for
} // end of for
} // end of if
printf("Average grade for all students in semester 1 is %0.2f \n", sums/(SIZE*6));
}
{
for(k = 0; k < SIZE; k++)
if(BENG[i].free == 0) // only print taken records
{
for(j = 0; j < 6; j++)
{
for(i = 0; i < SIZE; i++)
{
maxsums = BENG[i].results_semester_1[i];
}
if(maxsums>max)
{
max=maxsums;
}
}// end of for
}// end of if
}
printf("Max grade for all student in semester 1 is%d\n", max);
{
for(k = 0; k < SIZE; k++)
if(BENG[k].free == 0) // only print taken records
{
for(j = 0; j < 6; j++)
{
for(i = 0; i < 6; i++)
{
if(BENG[i].results_semester_1[i]<min)
{
min=BENG[i].results_semester_1[i];
}
}// end of for
}// end of for
}// end of if
}
printf("Min grade for all student in semester 1 is %d\n", min);
return ;
}
Use/Output:
./bin/student_database
1. To add a student
2. To delete a student
3. To display all students
4. Find a student using studentID
5. Find a student by student Surname
6. Find student would you like to run statistics for
7. Find statistics for all students
8. Display results of all students
9. Exit Program
1
Enter student ID (8-digits): 12345678
Enter firstname: Johnny
Enter surname: Walker
Enter year of course (1-4): 1
Enter course name: UnderwaterMusic
Enter result of semester 1 Module 1: 88.8
Enter result of semester 1 Module 2: 89.8
Enter result of semester 1 Module 3: 90.8
Enter result of semester 1 Module 4: 91.0
Enter result of semester 1 Module 5: 68.7
Enter result of semester 1 Module 6: 66.7
Enter result of semester 2 Module 1: 92.4
Enter result of semester 2 Module 2: 88.4
Enter result of semester 2 Module 3: 82.3
Enter result of semester 2 Module 4: 95.3
Enter result of semester 2 Module 5: 91.2
Enter result of semester 2 Module 6: 88.5
1. To add a student
2. To delete a student
3. To display all students
4. Find a student using studentID
5. Find a student by student Surname
6. Find student would you like to run statistics for
7. Find statistics for all students
8. Display results of all students
9. Exit Program
3
Student ID: 12345678:
Firstname: Johnny
Surname: Walker
Year: 1
Course: UnderwaterMusic
Result semester 1 Module 1: 88.80
Result semester 1 Module 2: 89.80
Result semester 1 Module 3: 90.80
Result semester 1 Module 4: 91.00
Result semester 1 Module 5: 68.70
Result semester 1 Module 6: 66.70
Result semester 2 Module 1: 92.40
Result semester 2 Module 2: 88.40
Result semester 2 Module 3: 82.30
Result semester 2 Module 4: 95.30
Result semester 2 Module 5: 91.20
Result semester 2 Module 6: 88.50
1. To add a student
2. To delete a student
3. To display all students
4. Find a student using studentID
5. Find a student by student Surname
6. Find student would you like to run statistics for
7. Find statistics for all students
8. Display results of all students
9. Exit Program
9
Quitting Program
Additional Suggestions
One suggestion I have for you is to not statically declare the string sizes in the function and just allocate as needed in add_student function. For example:
struct Student
{
long StudentID;//works
char *fname;//works
char *sname;//does not work
int year;//works
char *course;//works
float results_semester_1[6];//works
float results_semester_2[6];//works
int free; // 1 means its free, 0 means its not
};
Then you could simply allow scanf to dynamically allocate memory as needed with for example:
scanf("%m[^\n]%*c", &BENG[freepos].fname);
Additionally, you will see I had to change all the scanf format strings in add_student to prevent a newline from remaining in the input buffer (the result of pressing [enter]) causing your program to skip over the next input. Controlling the state of the input buffer is critical. There are a number of ways to do this, but taking a careful look at man scanf is a good place to start.
There's an error here
void search_for_student_by_name(sname) // just write the type of sname

Display the biggest cylinder capacity of all the cars in C — structures

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
char model[50], mark[50], color[50];
int cylinderCap;
} car;
void read(car *cr, int *nr) {
printf("Insert mark: ");
(*nr)++;
fflush(stdin);
gets((cr + *nr)->mark);
printf("Insert model: ");
gets((cr + *nr)->model);
printf("Insert color: ");
gets((cr + *nr)->color);
printf("Insert the cylinder capacity: ");
scanf("%d", &((cr + *nr)->cylinderCap));
}
void display(car *cr, int nr) {
printf("\n%-10s \t%-10s \t%-10s %d", (cr + nr)->mark, (cr + nr)->model,
(cr + nr)->color, cr[nr].cylinderCap);
}
void search_model(car *cr, int *nr, char mod[50]) {
int i;
for(i = 0; i <= (*nr); i++)
if(strcmp((cr + i)->model, mod) == 0)
display(cr, i);
}
void search_cc(car *cr, int *nr, int cc) {
int i;
for(i = 0; i <= (*nr); i++)
if((cr + i)->cylinderCap >= cc)
display(cr, i);
}
void clear(car *cr, int *nr, char mod[50]) {
int k = 0,i,j;
for(i = 0; i <= (*nr); i++)
if(strcmp((cr + i)->model, mod) == 0)
{
k++;
for(j = i; j <= (*nr - k); j++)
*(cr + j) = cr[j + 1];
}
*nr = *nr - k;
}
void main() {
car cr[50];
int opt, n = -1, i, cc = 1900;
char mod[50];
do{
system("CLS");
printf("1.Add a car\n");
printf("2.Display cars\n");
printf("3.Search a car after its model\n");
printf("4.Display all the cars with cc > 1900\n");
printf("5.Remove a car after its model\n");
printf("6.Exit\n");
printf("7.Display the biggest cyclinder capacity of all the cars\n");
printf("Insert option: ");
scanf("%d", &opt);
switch(opt) {
case 1:
read(&cr[0], &n);
break;
case 2:
printf("\n%-10s \t%-10s \t%-10s %s", "mark", "Model", "color", "Capacity");
for(i = 0; i <= n; i++)
display(cr, i);
break;
case 3:
printf("Insert model: ");
scanf("%s", mod);
printf("\n%-10s \t%-10s \t%-10s %s", "mark", "Model", "color", "Capacity");
search_model(&cr[0], &n, mod);
break;
case 4:
printf("\n%-10s \t%-10s \t%-10s %s", "mark", "Model", "color", "Capacity");
search_cc(&cr[0], &n, cc);
break;
case 5:
printf("Insert the model you wish to delete: ");
scanf("%s", mod);
clear(&cr[0], &n, mod);
break;
case 6:
break;
case 7:
break;
default: printf("Error! Please try another option!\n");
break;
}
getch();
}while(opt != 6);
getch();
}
This will display:
1.Add a car
2.Display cars
3.Search a car after its model
4.Display all the cars with cc > 1900
5.Remove a car after its model
6.Exit
7.Display the biggest cylinder capacity of all the cars
Insert option:
I don't have any idea how to do the last one, I don't even know how to begin!
I tried something like this, but with no success:
void maximum(car *cr, int *nr, int max) {
int i;
for(i = 0; i <- (*nr); i++)
if(((cr + i)->car) >=max))
max = (cr + i)->car;
display(max);
}
But it doesn't really work, so any help would be appreciated!
Your maximum function doesn't make any sense. You're trying to use an object type as an item for a struct, using superfluous pointer arithmetic and other things that were already discussed in the comments in your post.
void maximum(car *cr, int nr)
{
int i, max = 0;
for(i = 1; i <= nr - 1; i++)
{
if(cr[i].cilinderCap >= cr[max].cilinderCap)
{
max = i;
}
}
display(cr, max);
}
Note: try to understand my code before copying it to your file.
This is the most intuitive approach one can get. Note I'm using the "cylinder capacity" variable to actually check, uhm, the maximum cylinder capacity.
Also note that if you start your cars at index 0, you should search up to n - 1, and not n. The referenced parameter for nr is also redundant, as you don't even try to modify it.
So, you just call:
maximum(cr, n);
Another thing is that you should check for errors in the function, as in its current state, it might crash if there are no elements in the list.
There are some other "ethically incorrect stuff" in your code that are irrelevant to the question, but I recommend reading some articles on Google about struct lists.

Resources