So I wrote this code as a part of my assignment like so, we are still learning C language and I am just unable to correct this one. We have to make a code on writing a function to print the names of all the students that joined in a particular year.
It runs the code till switch case, but doesn't work further.
#include<stdio.h>
struct stdnt
{
char stName[100];
char stRNo[100];
char Dept[50];
char crse[50];
int YoJ[4];
}s[2];
void stYr(p)
{
printf("Student Name = %s\t",s[p].stName);
}
void stRNm(q)// q RNm
{
int i;
for(i=0;i<=1;i++)
{if(q == s[i].stRNo)
{
printf("Student Name = %s\t",s[i].stName);
printf("Student Year of Joining = %d\t",s[i].YoJ);
printf("Student Department = %s\t",s[i].Dept);
printf("Student Course = %s\n",s[i].crse);
}
}
}
int main()
{
int i;
int year;
int RNm;
int ch;
printf("Please Enter the details of 2 Students.\n");
for(i=0;i<=1;i++)
{
printf("Enter Name of Student %d:\n",i+1);
scanf("%s",s[i].stName);
printf("Enter Department of Student %d:\n",i+1);
scanf("%s",s[i].Dept);
printf("Enter Year of Joining of Student %d:\n",i+1);
scanf("%d",s[i].YoJ);
printf("Enter Roll Number of Student %d:\n",i+1);
scanf("%s",s[i].stRNo);
printf("Enter Course of Student %d:\n",i+1);
scanf("%s",s[i].crse);
}
printf("Enter 1 to Print the List of Student using Year.\nEnter 2 to Search the details of student using Roll no.\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the Year:\n");
scanf("%d",&year);
for(i=0;i<=1;i++)
{
if(year == s[i].YoJ)
{
stYr(i);
}
}
break;
case 2:
printf("Enter the roll number you want to search:\n");
scanf("%d",&RNm);
stRNm(RNm);
break;
}
return 0;
}
the question is
Create a structure to specify data on student given below : Roll number, Name, Department, Course, Year of Joining.
Assume that there are not more than 450 students (i am trying to code for 2 firstly will make it for 450 once it works)
also `
write a function to print name of all the students who joined in a particular year.
write another function to print the data of a student whose roll number is entered
make switch cases .
OUTPUT i am getting :
Please enter the details of 2 students .
Enter Name of Student 1:
katyal
Enter department :
Mech
Enter Year of joining:
2019
Enter roll number:
1
Enter Course :
C
Enter Name of Student 2:
Pranay
Enter department :
Mech
Enter Year of joining:
2019
Enter roll number:
2
Enter Course :
C
Enter 1 to Print the List of student using year
Enter 2 to print details of student using roll number
1
Enter the year:
2019
Process returned 0<0x0> execution time 30.600s
Press any key to continue.
Expected Output :
after the Year is entered after switch case, i expect the Function `stYr to get called and print the list of student with that Year as their Year of Joining
similarly if roll number is entered i want the details of that student printed.
As you're learning C code I think that you should start off by taking on board a few standard working practices.
It's very evident that either your teacher hasn't really coded in a working environment or they are expecting you to spot the mistakes.
I realise that there may be issues or restrictions due to your compiler, but here are some pointers that will help in future.
Here are some pointers based on your code.
Always initialise variables before use. If a variable can be null and that is not a valid value, check for null before use e.g. `char[] or pointer types.
Use typedef for structure declarations, this will allow the compiler to determine incorrect use through type checking during compilation.
Use long, meaningful variable and function names as an aid to understand the code.
Indentation with brackets e.g. { }, to make code easy to understand.
Refrain from using literal values in code as this can lead to introduction of bugs at a later stage if a value is not changed in all cases through the code.
Function parameters should be definitive in type - this makes code portable between compilers, environments and easier to understand.
In for loops try to only use less than < and greater than > comparisons.
In 'if' statements try to place non-assignable values on the left side as this will raise a compiler warning if you type = instead of ==.
Try and make functions re-entrant i.e. not reliant on global variables to determine their behaviour if possible, void func(void) should ring alarm bells.
Be careful when using signed values such as int use unsigned int in preference UNLESS you know that a variable will be assigned values of less than 0.
Declaring function parameters as const and then using local function variables as copies (if you wish to change their value) will make code easier to debug.
Switch statements should always include a default: to handle undetermined values.
struct stdnt /* REVIEW COMMENT: use typedef */
{
char stName[100]; /* REVIEW COMMENT: non-literal value for 100 */
char stRNo[100]; /* REVIEW COMMENT: Based upon later usage should this be unsigned int rather than char[] type */
char Dept[50];
char crse[50];
int YoJ[4]; /* REVIEW COMMENT: this is an array of int. Either use int or char[4] */
}s[2]; /* REVIEW COMMENT: separate out declaration for clarity and use a meaningful name */
I'd suggest that you change it to this
#define TEXT_LENGTH_LONG 100
#define TEXT_LENGTH_SHORT 50
#define NUMBER_OF_STUDENTS 2
typedef struct
{
char Name[NAME_LENGTH];
unsigned int RollNumber;
char Department[TEXT_LENGTH_SHORT];
char Course[TEXT_LENGTH_SHORT];
unsigned int YearOfJoining;
}student_t;
student_t students[NUMBER_OF_STUDENTS];
This function code has some issues.
void stRNm(q)/* REVIEW COMMENT: non-definitive declaration can cause confusion. Unclear function name and parameter */
{
int i;
for(i=0;i<=1;i++) /* REVIEW COMMENT: use of literal value makes maintenance more difficult and can introduce bugs if the array size is changed but this is missed */
{if(q == s[i].stRNo) /* REVIEW COMMENT: possible type mismatch in comparison - comparing int or char[] ?*/
{
printf("Student Name = %s\t",s[i].stName);
printf("Student Year of Joining = %d\t",s[i].YoJ);
printf("Student Department = %s\t",s[i].Dept);
printf("Student Course = %s\n",s[i].crse);
}
}
}
becomes
void PrintStudentInfo(const unsigned int rollNumOfStudent)/* Declaring rollNumOfStudent as const will give it compiler protection against being assigned to */
{
int i;
for(i=0;i<NUMBER_OF_STUDENTS;i++)
{
if(rollNumOfStudent == students[i].RollNumber)
{
printf("Student Name = %s\t",students[i].Name);
printf("Student Year of Joining = %d\t",students[i].YearOfJoining);
printf("Student Department = %s\t",students[i].Department);
printf("Student Course = %s\n",students[i].Course);
}
}
}
Okay this is just a start.
There are issues in your main function relating to what I've mentioned already that are causing the odd behaviour.
C is a language that is so loosely defined that it is very easy to introduce bugs due to shortcuts taken in coding.
Be pedantic.
Don't let the compiler make the decisions.
Be sure that the data types of variables are what you want rather than what the compiler determines.
Edit
Taking into account my comments about data types.
This line if(year == s[i].YoJ) is performing the following if(int == int[4])
Related
This is in C.
Im trying to create a function where you enter basic information and it assigns you an account number that can be used throughout.
When running the program it always out puts the same number. I dont need it to store outside of the program but the function and program are supposed to be run multiple times. I need this portion of the code to work because there is a later part where I have to delete the information entered and the way I thought best would be to assign the information to a value like account number and then use that to delete everything.
Sample output: Welcome Test Test to Global Bank. Your account number is 0 your initial balance in your checking is 100 and your initial balance in your savings is 1000.
What im trying to accomplish is have the account number in the sample output be 1 then when I run the NewAccount function again it should output:
Welcome Test2 Test2 to Global Bank. Your account number is 2 your initial balance in your checking is 100 and your initial balance in your savings is 1000.
This is the code. I have tried giving customers, of struct Bank a value of 20 (customers[20]) but that didnt seem to help. This is where im stuck at.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Customer
{
char FirstName[100];
char LastName[100];
int CheckingBalance;
int SavingsBalance;
int MoneyMarketBalance;
unsigned AccountNumber;
};
struct Customer NewCustomer(void)
{
static unsigned TopAccountNumber = 0;
struct Customer customer;
char FirstName[100];
char LastName[100];
int CheckingBalance;
int SavingsBalance;
int MoneyMarketBalance;
unsigned AccountNumber;
TopAccountNumber++;
customer.AccountNumber = TopAccountNumber;
return customer;
}
void NewAccount()
{
struct Customer customer;
printf("\nFirst name\n");
scanf("%s", customer.FirstName);
printf("\nLast name\n");
scanf("%s", customer.LastName);
printf("\nChecking deposit\n");
scanf("%d", &customer.CheckingBalance);
printf("\nSavings deposit\n");
scanf("%d", &customer.SavingsBalance);
printf("\nWelcome %s %s to Global Bank. Your account number is %d your initial balance in your checking is %d and your initial balance in your savings is %d.", customer.FirstName, customer.LastName, customer.AccountNumber, customer.CheckingBalance, customer.SavingsBalance);
}
int main()
{
int choice;
printf("\n1 is the problem function. After you enter your inital values run 1 again and run a second set of values \n to exit press '7'.\n");
while(1){
scanf("%d", &choice);
switch(choice)
{
case 1:
NewAccount();
break;
case 7:
printf("Have a good day and thank you for banking with Global Bank!\n");
exit(0);
}
}
}
A "bank" have customers, but isn't a customer in itself. So the Bank structure is rather badly named. And if one customer can only have a single account-number, then make it a part of the "customer" structure as well.
As for giving each customer a unique account number, one simple way is to keep track of the current highest number using a variable. Then when you create a new customer you increase that variable by one, and assign it to the customers specific account number.
For example:
struct Customer
{
// Other customer data...
unsigned AccountNumber;
};
struct Customer NewCustomer(void)
{
// This is the base for all account numbers
static unsigned TopAccountNumber = 0;
struct Customer customer;
// Initialize other customer data...
++TopAccountNumber; // Increase top account number
customer.AccountNumber = TopAccountNumber;
return customer;
}
first post here. Somewhat new to coding aswell.
Right now I'm at halt. What I need to do is get input from the user of an employee id then find it in a struct array variable, and keep asking until a correct one is entered.. all in a do-while loop. Then I need to print the salary of that employee and update it to something new.
I'm having a hard time trying to figure out how to search the struct array for that employee ID, then when that's done, saving what position the struct array in is so I can print THAT employees salary, then update it to something else.
Heres some code to show the struct array
#define SIZE 4
struct employee{
int id[SIZE] ;
int age[SIZE];
double salary[SIZE];
};
/* main program */
int main(void) {
struct employee emp[SIZE] = { 0 };
Here is some to show the code to what I've done
case 3: //Update Employee
printf("Update Employee Salary\n");
printf("======================\n");
int employid;
do{
printf("Enter Employee ID: ");
scanf("%d", &employid);
}while(employid != emp->id[SIZE]);
printf("The current salary is %lf", emp->salary[SIZE]);
break;
I know this is wrong. The While just looks at the current position, and the printf only prints the salary of the current arrays employee aswell.
Any help would be appreciated.
Bonus:
Notice when I'm assigning/working with my struct, I have to put "->" to actually tell my compiler that I'm pointing to that specific variable in the struct. Usually I put "." and have no idea why I need to put ->.. I just found the fix online.
Usually it would be "emp.id[SIZE];"
NOT "emp->id[SIZE];"
Anyone have any ideas?
Thanks all
Considering that your input to the structure is right, there are few things you can do.
The thing is you need to realize that you need a while/for loop to iterate over the employee array.
Second thing is, here you are not comparing it correctly. You are just comparing with the first element.
Now what you can do is
bool found = false;
int foundEmpId = -1;
do{
printf("Enter Employee ID: ");
scanf("%d", &employid);
for(size_t i = 0; i< SIZE; i++)
if( emp[i].id == employid ){
foundEmpId = employid;
found = true;
break;
}
}while(!found);
// do your work.
Now this is simply the O(n) searching.
Apart from that there is one thing you can see in my code. I am using emp[i].id. Here the structure I considered is
struct employee{
int id ;
int age;
double salary;
};
If you think of an employee these are the attributes you need to add over here. What you did was working with different groups of employees.
Here you will work like this
struct employee emps[SIZE];
...
...
// the attributes of employee will be inputted like this
// if( scanf("%d",&emps[i].id) == 1 ) { /* */ }
...
Why did you need emp->id[SIZE] here?
Dissecting the emp->id[SIZE] is equivalent to (*emp).id[SIZE] or more precisly emp[0].id[SIZE].
To summarize the problems/suggestion:-
P The portion of the code that you have shown it shows that you are not comparing with all the employees.
P You have created groups of employees. But you are not iterating or using all the groups. You just worked on first employee group.
S Instead of using the array of employee groups you should simply use array of employees. Or Even if you do use groups of enployess then just one group will suffice.
I've spent three hours trying to figure out why I'm getting a segmentation fault in this particular case & I went through a lot of questions on this topic but still I couldn't relate it to my case.
Now I seem to know what is the problem but I don't know why.
My array of structures doesn't seem to be initialized properly.
All the values which I take as input from the user are displayed properly in the main function but when I go inside the calc_bonus(..) function, it runs correct for i=0, but gives segmentation fault for i=1 & there on.
This was a simple assignment question which I solved successfully( got all the test cases right using a naive approach) but I want to know where my main solution went wrong.
Here's the initial code where I'm trying to find out netsalary & bonus.
#include <stdio.h>
#include <stdlib.h>
struct Employee
{
char empid[50];
int basicsalary;
int pf;
int mediclaim;
float salespercentage;
int bonus;
float netsalary;
};
int calc_NetSalary(struct Employee**,int);
int calc_Bonus(struct Employee**,int);
int main()
{
int n,i;
puts("Enter total records");
scanf("%d",&n);
struct Employee *emp = malloc(n*sizeof(*emp));
int flag[n];
for(i=0;i<n;i++)
{
puts("Enter the employee id");
scanf(" %[^\n]s",emp[i].empid);
puts("Enter the basic salary");
scanf("%d",&emp[i].basicsalary);
puts("Enter the PF amount");
scanf("%d",&emp[i].pf);
puts("Enter the mediclaim amount");
scanf("%d",&emp[i].mediclaim);
puts("Enter the sales percentage");
scanf("%f",&emp[i].salespercentage);
if(emp[i].basicsalary<0||emp[i].pf<0||emp[i].mediclaim<0||emp[i].salespercentage<0)
flag[i]=1;
else
flag[i]=0;
emp[i].bonus=calc_Bonus(&emp,i);
emp[i].netsalary=calc_NetSalary(&emp,i);
}
for(i=0;i<n;i++)
{
if(flag[i])
printf("Unable to calculate salary for the ID %s\n",emp[i].empid);
else
printf("Net salary for the ID %s is Rs.%.2f\n",emp[i].empid,emp[i].netsalary);
}
free(emp);
}
int calc_Bonus(struct Employee **emp,int i)
{
if(emp[i]->basicsalary<=7000 && emp[i]->salespercentage<=10)
return 1500;
else if(emp[i]->basicsalary<=7000 && emp[i]->salespercentage>=10)
return 3000;
else if(emp[i]->basicsalary<=15000 && emp[i]->basicsalary>7000 && emp[i]->salespercentage<=10)
return 2000;
else if(emp[i]->basicsalary<=15000 && emp[i]->basicsalary>7000 && emp[i]->salespercentage>=10)
return 4000;
else if(emp[i]->basicsalary>15000 && emp[i]->salespercentage<=10)
return 2500;
else if(emp[i]->basicsalary>15000 && emp[i]->salespercentage>=10)
return 4500;
}
int calc_NetSalary(struct Employee **emp,int i)
{
int a=emp[i]->basicsalary-emp[i]->pf-emp[i]->mediclaim+emp[i]->bonus;
return a;
}
Now I've tried to debug it by printing out the values of bonus & netsalary for different iterations & it works only for i=0
& gives 12 segmentation fault core dump.
Can anyone point out exactly what I'm doing wrong here?
I checked to see that emp variables had been initialised though the main problem starts at the second iteration when I call the calc_Bonus(..) function.
The value of emp[1].basicsalary gives that error but I don't know why.
EDIT:
What I did & got as output compared to what should be the output.
Enter total records
2
Enter the employee id
428
Enter the basic salary
5500
Enter the PF amount
550
Enter the mediclaim amount
1203
Enter the sales percentage
8.5
Enter the employee id
430
Enter the basic salary
12000
Enter the PF amount
350
Enter the mediclaim amount
650
Enter the sales percentage
10.5
/home/p10301/.vpl_launcher.sh: line 12: 11946 Segmentation fault (core dumped) ./vpl_execution
What the expected output should be:
Net salary for the ID 428 is Rs.5247.00
Net salary for the ID 430 is Rs.15000.00
Given emp declared in main() like so:
struct Employee *emp = malloc(n*sizeof(*emp));
, emp is a single pointer (as opposed to an array of pointers) to space large enough for several struct Employee objects; semantically, it points specifically to the first of those objects.
In that case, this call ...
calc_Bonus(&emp,i)
... and the similar call to calc_NetSalary(&emp,i) are consistent with those functions' prototypes, but inconsistent with their implementations and the joint meaning of their argument lists (as implied by their implementations) when i is nonzero. Specifically, consider this expression from calc_Bonus():
emp[i]->basicsalary
Since emp is declared there as a struct Employee **, let's rewrite that to replace the [] operation with the equivalent pointer-arithmetic based expression:
(*(emp + i))->basicsalary
Now the problem should be clearer, but you have to be careful to distinguish between the emp of calc_Bonus() and the emp of main(), which differ in both type and value. The emp in calc_Bonus(), as called, points to a scalar (emp of main()), so if you add a nonzero integer to it and attempt to dereference the result then you get undefined behavior.
Given the current function signature, that expression and all the similar ones would need to be rewritten in this form:
(*emp)[i].basicsalary
... or this one ...
(*emp + i)->basicsalary
But I think a better solution would be to reduce the level of indirection by rewriting the function like so:
int calc_Bonus(struct Employee *emp, int i) {
if (emp[i].basicsalary <= 7000 && emp[i].salespercentage <= 10)
return 1500;
// ...
}
and calling it from main() like so:
calc_Bonus(emp,i);
There are several other valid alternatives that would also be better than the original code.
Your calc_Bonus() method should not have the array and index number as parameters.
It should just have one parameter - a pointer to an instance of Employee.
And it need not return anything, since you are just filling in a field of that employee:
void calc_Bonus( Employee *e ) {
if(e->basicsalary<=7000 && e->salespercentage<=10) {
e->bonus = xxx;
} else if ( ... ) {
...
}
}
Then just call it using
calc_Bonus( &emp[i] );
You are allocating a sequence of struct Employee objects (i.e. malloc(n * sizeof(struct Employee)), but in function calc_bonus you treat them as an array of pointers to such struct Employee objects (and you pass a pointer to such a sequence of pointers, i.e. struct Employee**).
Hence, in function calc_bonus, when you write emp[i], then you get back the ith pointer in emp. But emp does not contain pointers, it contains the employee objects. So emp[i] will return a value that is treated as a pointer, but the pointer value will point to something arbitrary, which is very likely on a struct Employee-object. And dereferencing such an "invalid" pointer yields undefined behaviour, which might become visible as a segmentation fault.
To overcome this, define and use calc_Bonus as follows:
int calc_Bonus(struct Employee[],int);
int calc_Bonus(struct Employee emp[],int i)
{
if(emp[i].basicsalary<=7000 && emp[i].salespercentage<=10) {
...
}
int main () {
...
emp[i].bonus=calc_Bonus(emp,i);
}
Disclaimer: This is my first question on StackOverflow and I'm a novice programmer, so my apologies ahead of time if you are appalled by my code or if I don't post my question appropriately.
Anyways, I'm working on a gradebook with dynamically allocated structures. I've divided the gradebook into three structues, a student structure (student name, student id), a course structure (course name, course id), and an enroll structure(student id, course id, grade).
Problem: I'm able to input as many grade as I need without errors for the first student. When I try to input a grade for the second student my program core dumps. I've checked all the variables involved to see if they are passed to my function appropriately and they are. The following is my Enroll structure and my add grade function.
typedef struct {
int Student_ID;
int Course_ID;
int *Grade;
int GradeCount;
} Enroll_Database;
Function...
void addGrade(Enroll_Database *Enroll)
{
int i = 0, j = 0, b, Course_Num, Student_Num, Grade;
printf("Enter Course Number: ");
scanf("%d", &Course_Num);
printf("Enter Student ID: ");
scanf("%d", &Student_Num);
/* For loop that traverses through the Enroll array until until it encounters
nothing in the Course ID */
for(i = 0; Enroll[i].Course_ID != 0; i++)
{
/* if the Student Number and the Course Number are equal to their
appropriate Enroll element, then ask user to input Grade */
if(Enroll[i].Student_ID == Student_Num && Enroll[i].Course_ID == Course_Num)
{
printf("Enter Grade: ");
scanf("%d", &Grade);
if(Enroll[i].GradeCount == 0)
{
Enroll->Grade = (int *) malloc(sizeof(int));
Enroll[i].Grade[Enroll[i].GradeCount] = Grade; //core dumps
Enroll[i].GradeCount++;
}
else
{
Enroll->Grade = (int *) realloc(Enroll->Grade, sizeof(int));
Enroll[i].Grade[Enroll[i].GradeCount] = Grade; //core dumps
Enroll[i].GradeCount++;
}
}
}
}
I've ran multiple checks and the core dump occurs after I malloc/realloc and assign user input to the grade value in the enroll structure.
I'd greatly appreciate any help, and I'm sorry again if my code is unreadable or I formatted wrong.
Thanks!
This only allocates space for one element,. and also it reallocates the wrong pointer:
Enroll->Grade = (int *) realloc(Enroll->Grade, sizeof(int));
It could be fixed like this:
Enroll[i].Grade = realloc(Enroll[i].Grade, sizeof(int) * (Enroll[i].GradeCount + 1));
Remembering that X->Y, (*X).Y, and X[0].Y all mean the same thing: your original version actually reallocated Enroll[0].Grade, instead of Enroll[i].Grade.
(The rest of this answer is some possible style improvement suggestions:)
To avoid this sort of error, I'd personally write just after the scanf:
Enroll_Database *found = &Enroll[i];
and then use found-> everywhere instead of Enroll[i]. Alternatively I'd consider having a separate function to actually add the grade (which is called once the database entry has been found).
Now, if you initialize Enroll[i].Grade to NULL when setting up the database, you actually wouldn't need this if...else statement. Since the behaviour of realloc(NULL, X) is the same as malloc(X), the same code would handle both situations.
Note that in C you should not cast the value returned by malloc and friends.
Another thing to bear in mind is that the style X = realloc(X, ... does not allow you to recover from allocation failure. To write robust code you need to take some sensible action when a malloc-family function returns NULL; this could be as simple as printing a message and calling exit.
I'm learning Structures in C, and trying to write the solution for this problem-
Create a structure to specify data on students given below: Roll
number, Name, Department, Course, Year of joining .
Assume that there are not more than 5 students in the class. (a) Write a function to
print names of all students who joined in a particular year. (b) Write
a function to print the data of a student whose roll number is given.
My code is given next, with a brief description of various components in the program, and then the source of the problem -
#include<stdio.h>
struct student
{
int roll_no;
char name[20];
char department[30];
char course[20];
int year_joined;
};
void main()
{
struct student s[5];
int i=0,choice;
printf("\n Enter the following information for each student: \n");
printf("\n Roll No., Name, Department, Course, Year of Joining\n");
for(i=0;i<=4;i++)
scanf("%d %s %s %s %d", &s[i].roll_no, &s[i].name, &s[i].department, &s[i].course, &s[i].year_joined);
printf("\n Please choose from the following options :\n");
printf("\n 1. Print names of students who joined in a given year.");
printf("\n 2. Print data of all students whose roll.no is given.");
scanf("%d",&choice);
switch(choice)
{
case 1: display_names(s);
break;
case 2: student_data(s);
break;
default: printf("\n Incorrect choice, please try again.");
}
}
void display_names(struct student p[])
{
int i,count=0;
int year;
printf("\n Enter the year you wish to search student info. for : \n");
scanf("%d",&year);
for(i=0;i<=4;i++)
{
if(p[i].year_joined==year)
{
//printf("%d %s %s %s %d", p[i].roll_no, p[i].name, p[i].department, p[i].course, p[i]. year_joined);
count++;
printf("\n Student Name: %s\n", p[i].name);
}
}
printf("\n Total Number of students who joined in the year %d is %d\n", year,count);
if(count==0)
printf("\n No match found.");
}
void student_data(struct student st[])
{
int i,count=0;
int roll;
printf("\n Enter roll number of the student: \n");
scanf("%d",&roll);
for(i=0;i<=4;i++)
{
if(st[i].roll_no=roll)
{
count++;
printf("\n Student Data: Roll No. Name Department Course Year of Joining \n");
printf("\n %d %s %s %s %d", st[i].roll_no, st[i].name, st[i].department, st[i].course,st[i].year_joined);
break;
}
}
if(count==0)
printf("\n No matching Roll Numbers found\n");
}
Here's a brief description of this program-
Since I'm required to store information about multiple students in the structure, I have created a structure array. The structure struct student is defined at the very beginning, and the array is created inside main- struct student s[5]
The structure is initialized by accepting user input through scanf() inside main(). There are two switch cases for the two functions, asked in the question- display_names(s) and student_data(s)
The display_names(s) function is called in main, and is defined outside it. The function accepts a structure array and asks the user to enter a year. It loops through the initialized array and searches for the input(year of joining) entered by the user. When there's a match, it prints out the names of all students who've joined in that year. Here's a sample output for this function-
*
**Enter the following information for each student:
Roll No., Name, Department, Course, Year of Joining
10 Tim CS MS 2013
20 Shane CS MS 2013
30 John EE ME 2013
40 Mark MECH MS 2013
50 Matt EE ME 2010
Please choose from the following options :
1. Print names of students who joined in a given year.
2. Print data of all students whose roll.no is given.1
Enter the year you wish to search student info. for :
2013
Student Name: Tim
Student Name: Shane
Student Name: John
Student Name: Mark
Total Number of students who joined in the year 2013 is 4**
*
This function works fine.
The problem is in the next function student_data(). Similar to the first function, it accepts a structure array as input. The way I've designed the function- the idea is to loop through the array until it finds a roll number that's equal to the one entered by the user. When there's a match, it would print out the details of that particular student itself. However, as it stands, this function always prints the first entry in the array, and I can't seem to understand why. I've added the break in the if statement, but it doesn't seem to make any difference.
Here's a sample output-
Enter the following information for each student:
Roll No., Name, Department, Course, Year of Joining
10 Tim CS MS 2013
20 Shane CS MS 2013
30 John EE ME 2013
40 Mark MECH MS 2013
50 Matt EE ME 2010
Please choose from the following options :
1. Print names of students who joined in a given year.
2. Print data of all students whose roll.no is given.2
Enter roll number of the student:
40
Student Data: Roll No. Name Department Course Year of Joining
40 Tim CS MS 2013
Can you please say where I'm going wrong in this second function?
Your if statement within student_data() is assigning rather than comparing.
Consider compiling with the -Wall ( or specifically -Wparentheses ) flag:
#include <stdio.h>
int main( void )
{
int a = 10;
if ( a = 11 ) printf( "a equals 11\n" );
return 0;
}
Using -Wall:
$ gcc main.c -Wall
warning: suggest parentheses around assignment used as truth value [-Wparentheses]
if ( a = 11 ) printf( "a equals 11\n" );
$