Time to combine everything: structures, arrays, functions, pointers, strings and a menu loop. You will build a small Student Record System - the kind of project asked in first-year practicals and viva exams.
What the program does#
- Add a student (roll number, name, marks)
- Display all students in a table
- Search a student by roll number
- Show the topper and the class average
- Exit
Step 1: the data model#
#define MAX 100
typedef struct {
int roll;
char name[30];
int marks;
} Student;
All records live in Student list[MAX], and int count says how many are filled.
Step 2: one function per menu option#
void addStudent(Student list[], int *count)- reads one record and increments*count(pointer, because it must changecountin main).void display(const Student list[], int count)- prints a table.int findByRoll(const Student list[], int count, int roll)- returns the index or -1.void report(const Student list[], int count)- topper and average.
बड़े program को छोटे-छोटे functions में बाँटिए - हर menu option के लिए एक function। count बदलना है तो उसका address (&count) भेजिए। जो function data सिर्फ़ पढ़ते हैं, उनमें const लिखिए ताकि गलती से data न बदले।
Step 3: the complete program#
The input box below simulates a user typing menu choices: add three students, display, search roll 102, report, exit. Change the input to try other choices.
Added Aarav Added Diya Added Kabir Roll Name Marks 101 Aarav 72 102 Diya 88 103 Kabir 65 Found: Diya, marks 88 Topper: Diya (88) Class average: 75.00 Goodbye!
How it works#
- The
do-whileloop keeps showing the menu until choice5. Student *s = &list[*count];gives a pointer to the next free slot, sos->rollwrites straight into the array.const Student list[]documents thatdisplayandreportnever modify the data.findByRollreturns-1for "not found" - a common C convention.
Ideas to extend it#
- Save and load the records to a file with
fprintf/fscanfso data survives restarts. - Delete a student (shift the later records one place left).
- Grades - add a
char grademember computed from marks. - Dynamic size - replace the fixed array with
malloc/realloc. - Sort the list by marks or name (see the exercises).
In a viva, be ready to explain: why count is passed as a pointer, the difference between . and ->, why strcmp is needed for names, and what happens if more than MAX students are added.
Summary#
You used typedef struct, arrays of structures, functions with pointer parameters, const, string input and a menu loop with switch - the core of C programming. Next, try the C++ course to see how classes make this kind of program even cleaner.