Data Structures/Records - c

My current program looks like this. This program should ask 5 records of a person and display them.
#include<stdio.h>
struct rec {
char name[100],address[100];
double age,mobileno;
}x;
main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
{
printf("Enter Your Name: ");
scanf("%s",&x.name);
printf("Enter Your Age: ");
scanf("%lf",&x.age);
printf("Enter Your Address: ");
scanf("%s",&x.address);
printf("Enter Your Mobile No.: ");
scanf("%lf",&x.mobileno);
}
printf("\n\nThe Information has been added");
printf("\n\nNAME AGE ADDRESS MOBILE NUMBER");
for(i=1;i<=5;i++)
{
printf("\n%s %.0lf %s %.0lf",x.name,x.age,x.address,x.mobileno);
}
getch();
}
I have a problem in displaying the 5 different record. How do I display the five records in one printf?

You simply need a collection of structures to save the data into, currently you're just overwriting the data each time. There are a lot of ways to do this, but you could do something like use a static array, for example:
struct rec {
char name[100],address[100];
double age,mobileno;
};
int main() {
struct rec records[5];
for(i=0;i<5;i++) // <-- note this is 0 to 4, not 1 to 5
{
printf("Enter Your Name: ");
scanf("%s",records[i].name); // <-- don't add the & for the string input
Same for the printf() further down:
for(i=0; i<5; i++)
{
printf("Name is: %s\n", records[i].name);

Related

how to print all id names in one loop?

This code is about 'struct' in C..
I created a struct with the properties name,roll etc.. By using the for-loop I let the user to create the struct objects. they are named as student,employee, faculty
the problem is the objects are created. But I can use them only inside the for-loop. If I want to get the value of all names in main function, it doesn't work. How can I solve it?How do i print all names in the code in only one loop
what will be the logic
#include<stdio.h>
#include<conio.h>
struct student
{
int std;
char fee[90]; //Collect Data of students
int rollno;
char name[15];
char sub[100];
};
main()
{
int x;
printf("******Enter the total number of Student from HOD*******:\n");
scanf("%d",&x);
struct student a[x];
for(int i=0;i<x;i++)
{
printf("\nEnter Rollno:\t");
scanf("%d",&a[x].rollno);
printf("\nEnter name:\t");
scanf("%s",&a[x].name);
printf("\nIs Fee Submitted:\t");
scanf("%s",&a[x].fee);
printf("\nEnter Subject name:\t");
scanf("%s",a[x].sub);
}
printf("\n****Display All Student names****");
for(int i=0;i<x;i++)
{
printf("\n%s",a[x].name);
}
//Faculty
struct faculty
{
char Fname[100];
char Sname[100];
};
int y;
printf("\n\n********Please HOD enter the total faculty members********\n");
scanf("%d",&y);
struct faculty b[y];
for(int j=0;j<y;j++)
{
printf("\nEnter Faculty Member Name:\t");
scanf("%s",&b[y].Fname);
printf("\nEnter their Subjects:\t");
scanf("%s",&b[y].Sname);
}
printf("\n****Display all Faculty Member Name****");
for(int j=0;j<y;j++)
{
printf("\n%s",b[y].Fname);
}
// Employes
struct employes
{
char ename[100];
char rank[100];
};
int z;
printf("\n\n********please HOD enter the total no of Employes*******:\n");
scanf("%s",&z);
struct employes c[z];
for(int j=0;j<y;j++)
{
printf("\nEnter the Employe name:\t");
scanf("%s",&c[y].ename);
printf("\n and enter their ranks:\t");
scanf("%s",&c[y].rank);
}
printf("\n****Display all Employe names****");
for(int j=0;j<y;j++)
{
printf("%s\n",c[y].ename);
}
}
#include<stdio.h>
#include<conio.h>
struct student
{
int std;
char fee[90];
int rollno;
char name[15];
char sub[100];
};
main()
{
int x;
printf("******Enter the total number of Student from HOD*******:\n");
scanf("%d",&x);
struct student a[x];
for(int i=0;i<x;i++)
{
printf("\nEnter Rollno:\t");
scanf("%d",&a[x].rollno);
printf("\nEnter name:\t");
scanf("%s",&a[x].name);
printf("\nIs Fee Submitted:\t");
scanf("%s",&a[x].fee);
printf("\nEnter Subject name:\t");
scanf("%s",a[x].sub);
}
printf("\n****Display All Student names****");
for(int i=0;i<x;i++)
{
printf("\n%s",a[x].name);
}
struct faculty
{
char Fname[100];
char Sname[100];
};
int y;
printf("\n\n********Please HOD enter the total faculty members********:\n");
scanf("%d",&y);
struct faculty b[y];
for(int j=0;j<y;j++)
{
printf("\nEnter Faculty Member Name:\t");
scanf("%s",&b[y].Fname);
printf("\nEnter their Subjects:\t");
scanf("%s",&b[y].Sname);
}
printf("\n****Display all Faculty Member Name****");
for(int j=0;j<y;j++)
{
printf("\n%s",b[y].Fname);
}
struct employes
{
char ename[100];
char rank[100];
};
int z;
printf("\n\n********Please HOD enter the total no of Employes*******:\n");
scanf("%d",&z); //You used %s instead of %d
struct employes c[z];
for(int j=0;j<z;j++) //You used wrong variable 'y' here
{
printf("\nEnter the Employe name:\t");
scanf("%s",&c[z].ename); //You used wrong variable 'y' here
printf("\nEnter their ranks:\t");
scanf("%s",&c[z].rank); //You used wrong variable 'y' here
}
printf("\n****Display all Employe names****");
for(int j=0;j<z;j++) //You used wrong variable 'y' here
{
printf("\n%s",c[z].ename); //You used wrong variable 'y' here
}
}
Errors:
Wrong format specifier used in taking integer input in number of Employees.
Wrong loop variable used in all loops of Employee.
Now this code is working. I've pointed out the errors in the comments also.
The loop increases i from 0 to some other value x.
(lets say x is 5 for this example)
So i has values 0, 1, 2, 3....
But regardless, you only put data into one element of the array: 5
And you keep overwriting that same element over and over again.
And 5 isn't even a valid index!! The valid indicies are 0, 1, 2, 3, 4.
5 is one-past the end of the array!

Searching for a match in a structure array

I've been at this mess for a while and I still haven't figured out where I'm going wrong with it, totally knifing myself if it's something ridiculous like a pointer.
Task shown: Trying to fill a structure array with student ID, name, last name, date of birth, and grades.. Then search by a matching ID that's given to the user.
I'd highly appreciate any help related to this subject, I've been seriously stuck at it for a while. Also I apologize in advance for the french parts
// Part 1
struct Date{
int day;
int month;
int year;
};
// Part 2
struct Student{
int ID;
char name[20];
char lastname[20];
struct Date DOB;
int notes[J];
};
// Part 3
void FillStudentList(struct Student E){
int i;
printf("\nInsert ID: ");
scanf("%d", &E.ID);
printf("Insert name: ");
scanf("%s", &E.name);
printf("Insert last name: ");
scanf("%s", &E.lastname);
printf("Insert date of birth: ");
scanf("%d %d %d", &E.DOB.day, &E.DOB.month, &E.DOB.year);
printf("Insert notes: ");
for(i=0; i<J; i++)
scanf("%d", &E.Notes[i]);
}
// Part 4
void ShowByNb(int Nb, struct Student E[], int NbStudents){
int j, i;
for(i=0; i<NbStudents; i++){
if (E[i].ID== Nb){
printf("\nID: %d", E[i].ID);
printf("\nName: %s", E[i].name);
printf("\nLast Name: %s", E[i].lastname);
printf("\nDate Of Birth: %s-%s-%s", E[i].DOB.day, E[i].DOB.month, E[i].DOB.year);
printf("\nNotes: ");
for(j=0; j<J; j++){
printf("%d", E[i].Notes[j]);
}
}
else
printf("\nInvalid Student!\n");
}
}
// Part 5
void main(){
int i, x;
struct Student E[N];
for(i=0; i<N; i++){
printf("\n\nStudent #%d", i+1);
FillStudentList(E[i]);
}
printf("\n\nSearch student by NB: ");
scanf("%d", &x);
ShowByNb(x, E, N);
}
The edited code below, I believe, achieves your goal. The main problem (other than reading/printing 'int's with '%s' was how you pass your structure to your functions. It is necessary to pass the structure by reference so that its values can be seen outside of the FillStudentList function; see this link.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define N 2
#define J 2
// Part 1
struct Dat{
int jour;
int mois;
int annee;
};
// Part 2
struct Etudiant{
int numero;
char nom[20];
char prenom[20];
struct Dat DDN;
int Notes[J];
};
// Part 3
/* Modified this so that a pointer to the struct is passed instead of a copy of the struct */
void FillStudentList(struct Etudiant *E){
int i;
printf("\nInsert ID: ");
scanf("%d", &E->numero);
printf("Insert name: ");
scanf("%s", E->nom);
printf("Insert last name: ");
scanf("%s", E->prenom);
printf("Insert date of birth: ");
/* These are integers. Do not read with %s */
scanf("%d %d %d", &E->DDN.jour, &E->DDN.mois, &E->DDN.annee);
printf("Insert notes: ");
for(i=0; i<J; i++)
scanf("%d", &E->Notes[i]);
}
// Part 4
void ShowByNb(int Nb, struct Etudiant E[]){
/* Don't redefine N == NbEtudiants making it seem that N is variable */
int j, i;
for(i=0; i<N; i++){
if (E[i].numero == Nb){
printf("\nID: %d", E[i].numero);
printf("\nName: %s", E[i].nom);
printf("\nLast Name: %s", E[i].prenom);
/* Again, can't print integers with %s */
printf("\nDate Of Birth: %d-%d-%d", E[i].DDN.jour, E[i].DDN.mois, E[i].DDN.annee);
printf("\nLes notes: ");
for(j=0; j<J; j++){
printf("%d ", E[i].Notes[j]);
}
return;
}
/* Your previous else would print invalid student every time you ran through the loop even
* if the student number was valid for a later student.
*/
}
/* Only print this if student was not found in any of the N Student structures */
printf("\nInvalid Student!\n");
}
// Part 5
void main(){
setbuf(stdout, NULL);
int i, x;
struct Etudiant E[N];
for(i=0; i<N; i++){
printf("\n\nStudent #%d", i+1);
FillStudentList(&E[i]);
}
printf("\n\nSearch student by NB: ");
scanf("%d", &x);
ShowByNb(x, E);
}
Input
1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2
Output
Student #1
Insert ID: 1
Insert name: 1
Insert last name: 1
Insert date of birth: 1
1
1
Insert notes: 1
1
Student #2
Insert ID: 2
Insert name: 2
Insert last name: 2
Insert date of birth: 2
2
2
Insert notes: 2
2
Search student by NB: 2
ID: 2
Name: 2
Last Name: 2
Date Of Birth: 2-2-2
Les notes: 2 2
classic mistake: passing parameter by value instead of by reference:
void FillStudentList(struct Student E){
.....
}
What happens here is that a local copy of your structure is created on the stack, populated with whatever the input is and destroyed when the function exits.
Generally in C, even if you don't want to modify the structure, you pass struct parameters by pointer; if you pass them by value each member of the structure is copied on to the stack...which is a waste of time an memory.
So changing the function prototype (and the code to work with the new signature) should fix the issue:
void FillStudentList(struct Student *E){
....
}

C: Array of Structs (Input into int array within array of structs)

Hi I have to create a database that stores students number, name and also stores an array of course marks (1-N) in C Programming Language.
Everything worked until I started coding for the array of course marks. Then every time I compiled the code it kept crashing as soon as it asked to input the course marks.
Can you please tell me where I'm going wrong in my programming for this task? I have attached it to this message.
The program worked for inputting the name, student number, however I could not get the program to input array of marks. I have asked how many course marks to be entered and then used a for loop within the "void insert(void)" function to keep inputting the course marks into the array *marks. I am referring specifically to lines 24 to 30 in my programming code.
Always at this point the program kept crashing and I could not proceed further to enter more names or print the stored student details.
I think there is a problem with this part:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n");
scanf("%d", &(list[num_students].marks[num_marks]));
}
Anyway here is the full code:
#include <stdio.h>
#include <string.h>
struct student{
int number;
char name[10];
int marks[5];
};
struct student list[10];
int num_students = 0;
int num_marks = 0;
int *p;
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++; // HOW DO WE INPUT ARRAY MARKS??? MARK1: , MARK2: , MARK3 ,
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
int main(void)
{
int code;
int opt1;
int courses, i, k, j, counter;
for (;;){
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) DISPLAY REPORT OF ALL STUDENTS: \n");
scanf(" %d", &code);
switch (code){
case 1 :
insert();
break;
case 2 :
printtest();
break;
default:
printf("Illegal code\n");
printf("\n");
}
}
}
Apart from what others pointed out, I'd like to draw your attention towards the following:
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++;
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
There are three problematic statements:
scanf("%s", &list[num_students].name); This is why beginners should use compilers with all warnings enabled.
printf("Mark: %d /100 \n", list[i].marks); What did you declare marks as in the first place?
scanf("%d", num_marks); Seems like you put & operator where not needed and ignore where needed. Read your textbook before asking a question next time.
Seems like you're having a tough time understanding the concept of arrays and pointers. Read your text book thoroughly before venturing into the world of pointers. If you don't use them correctly, even compiler can't help you.
Also, even if I don't expect your program to have a robust input mechanism, at least array bounds checking is expected. Learn good habits from the beginning. They'll save a lot of your time while debugging later.
Seems to be an error in:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
The crash is probably because num_marks as index indexes beyond the array. Change to:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[i]));
}

how to sort specific in structs and search by last name

I want to know how I could sort elements in structs by score and search by last name.
The program also has a problem; when I enter 1 to print the records it asks me for a new entry and when I press 2 it prints the records and ask me for the entry.
So same thing for both cases — I don't know why?
#include <stdio.h>
#include <stdlib.h>
struct the_struct
{
char FirstName[20];
char LastName[32];
int Score[20];
};
int main ()
{
int i,n,z;
struct the_struct *ptr[100];
printf("how many students?\n");
scanf("%d",&n);
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);
}
printf("Enter the command you want to proceed to.\nprint record (press 1)\nadd new records (press 2)\ndelete record (press 3)\nSearch by last name (press 4)\nSort by score(press 5)\nSort by last name( press 6)\nFind Median score(press 7)\nExit program (press 0)\n");
scanf("%d",&z);
if (z==1);
{
for (i = 0; i<n;++i)
{
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
}
}
if (z==2);
{
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);
}
}
So I tried to write the sort function but it doesn't work when I print it.
if (z==5)
{
if(strcmp(The_final[i].Score,The_final[i+1].Score)>0)
{
temp = The_final[i];
The_final[i] = The_final[i+1];
The_final[i+1] = temp;
}
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
}

C store values in an array

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", &param[i].timedate.day);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.month);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.year);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.hour);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.minute);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.second);
printf("enter time %d:", i+1);
scanf("%d", &param[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 = &param[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;
}

Resources