Table of Contents

    Practice Assignment: Save Student Records in a File

    Chapter 17.9

    Practice Assignment: Save Student Records in a File

    Practice file handling by designing a small program that stores student records in a file. This assignment will help you apply reading files, writing files, appending files, file paths, CSV basics, JSON basics, validation, and simple data storage concepts.

    Assignment Introduction

    In this practice assignment, you will create a simple program to save student records in a file. This assignment is designed to help you understand how programs store data permanently using file handling.

    Until now, you have learned about reading files, writing files, appending files, file paths, text files, binary files, CSV, JSON, and database introduction. Before moving deeper into database systems, it is important to understand how simple data can be stored in files.

    In real-world applications, file storage is often used for small records, logs, exports, reports, configuration settings, and beginner-level data storage projects. This assignment will help you build a small file-based student record system.

    "A file-based student record system teaches how data can be collected, formatted, saved, read, and reused later."

    Assignment Objective

    The main objective of this assignment is to create a program that accepts student details and saves them into a file in a structured format.

    Students should understand how data is collected from a program and stored permanently in a file so that it can be opened, read, or processed later.

    Learning Objectives

    • Understand how to save user data into a file.
    • Practice writing data to a text file.
    • Practice appending new records without deleting old records.
    • Use proper file paths for storing records.
    • Store student records in a structured format.
    • Understand the difference between overwriting and appending data.
    • Validate student data before saving it.
    • Read saved student records from a file.
    • Display file data in a readable format.
    • Understand why CSV and JSON formats are useful for records.

    Prerequisites

    Before attempting this assignment, students should understand the following topics.

    Prerequisite Topic Why It Is Needed
    Variables and Data Types To store student name, roll number, course, marks, and grade.
    Input and Output To accept student details and display saved records.
    Conditional Statements To validate marks and calculate grade.
    Loops To save multiple student records and read records line by line.
    Functions / Methods To organize code into reusable parts such as saveStudent() and displayStudents().
    Reading Files To read saved student records from the file.
    Writing Files To create a file and save student data.
    Appending Files To add new student records without deleting old records.
    CSV and JSON Basics To save records in a structured file format.

    Problem Statement

    Design a simple program named Student Record Saver. The program should accept student details from the user and save those details into a file.

    "Create a program that stores student records in a file. Each student record should include roll number, name, course, marks, grade, and pass/fail status."

    The program should allow the user to add student records and view saved student records. The records should remain available even after the program stops because they are saved in a file.

    Functional Requirements

    Functional requirements describe what the program should do.

    Required Features

    • Accept student roll number.
    • Accept student name.
    • Accept course name.
    • Accept marks.
    • Validate that marks are between 0 and 100.
    • Calculate grade based on marks.
    • Determine pass or fail status.
    • Save student record into a file.
    • Append new student records without deleting old records.
    • Read and display all saved student records.
    • Show proper messages when data is saved successfully.
    • Handle file-related errors properly.

    Non-Functional Requirements

    Non-functional requirements describe how the program should be designed.

    Design Requirements

    • The program should be easy to understand.
    • The code should be clean and properly organized.
    • Variable names should be meaningful.
    • File names should be clear and descriptive.
    • File paths should be simple and easy to manage.
    • Student records should follow a consistent format.
    • File errors should be handled with clear messages.
    • Data should not be accidentally overwritten when adding new records.
    • The solution should be extendable for future features.

    Recommended File Structure

    Students should organize project files properly. A simple folder structure can look like this:

    
    StudentRecordSaver
    │
    ├── program-file
    │
    └── data
        └── students.csv
    

    In this structure:

    • program-file represents the source code file of any programming language.
    • data is a folder used to store data files.
    • students.csv stores student records.
    Recommended: Store student records inside a separate data folder. This keeps the project organized and easy to manage.

    Suggested File Format: CSV

    For this assignment, CSV is a good file format because student records are table-like data. Each record can be stored as one row, and each value can be separated by commas.

    CSV FORMAT
    One Student becomes One CSV Row

    Suggested CSV structure:

    
    rollNumber,name,course,marks,grade,status
    101,Rahul,Programming Fundamentals,85,B,Passed
    102,Ayesha,Programming Fundamentals,92,A,Passed
    103,John,Programming Fundamentals,35,Fail,Failed
    

    The first row is the header row. It defines the column names. Each next row represents one student record.

    Optional File Format: JSON

    Students can also try storing student records in JSON format after completing the CSV version. JSON is useful when data needs to be more descriptive or structured.

    
    [
        {
            "rollNumber": 101,
            "name": "Rahul",
            "course": "Programming Fundamentals",
            "marks": 85,
            "grade": "B",
            "status": "Passed"
        },
        {
            "rollNumber": 102,
            "name": "Ayesha",
            "course": "Programming Fundamentals",
            "marks": 92,
            "grade": "A",
            "status": "Passed"
        }
    ]
    
    Beginner Recommendation: Start with CSV first because it is simpler for table-like student records. Try JSON as an extension task.

    Grade Calculation Rule

    The program should calculate grade based on marks. Students can use the following grading system:

    Marks Range Grade Status
    90 to 100 A Passed
    75 to 89 B Passed
    60 to 74 C Passed
    40 to 59 D Passed
    0 to 39 Fail Failed

    Validation Rules

    Data validation is important before saving records into a file. If invalid data is saved, the file becomes unreliable and difficult to process later.

    Required Validation Rules

    • Roll number should not be empty.
    • Name should not be empty.
    • Course name should not be empty.
    • Marks should be a number.
    • Marks should be between 0 and 100.
    • Student record should follow the same column order every time.
    • File should be opened in append mode when adding a new record.

    Assignment Task 1: Create Student Data Fields

    Create variables or properties to store student details.

    Required Fields

    • rollNumber
    • studentName
    • courseName
    • marks
    • grade
    • status
    
    // Conceptual fields
    
    rollNumber
    studentName
    courseName
    marks
    grade
    status
    

    These fields will be used to create one complete student record.

    Assignment Task 2: Accept Student Input

    The program should accept student details from the user. The exact input syntax depends on the programming language used.

    
    // Conceptual input logic
    
    read rollNumber
    read studentName
    read courseName
    read marks
    

    After accepting marks, the program should validate the marks before calculating grade.

    Assignment Task 3: Validate Marks

    Marks should be between 0 and 100. If marks are less than 0 or greater than 100, the program should show an error message and should not save the invalid record.

    
    // Conceptual validation logic
    
    if marks < 0 or marks > 100
        show "Invalid marks. Marks must be between 0 and 100."
        do not save record
    else
        continue processing
    
    Avoid Do not save records with invalid marks such as -10 or 150.

    Assignment Task 4: Calculate Grade and Status

    Create logic to calculate grade and pass/fail status based on marks.

    
    // Conceptual grade calculation
    
    if marks >= 90
        grade = "A"
    else if marks >= 75
        grade = "B"
    else if marks >= 60
        grade = "C"
    else if marks >= 40
        grade = "D"
    else
        grade = "Fail"
    
    if marks >= 40
        status = "Passed"
    else
        status = "Failed"
    

    This logic should be placed inside a function or method if possible.

    Assignment Task 5: Save Student Record to File

    After collecting and validating data, save the student record into a file. The file should be opened in append mode so that old records are not deleted.

    
    // Conceptual save logic
    
    open "data/students.csv" in append mode
    
    write rollNumber + "," + studentName + "," + courseName + "," + marks + "," + grade + "," + status
    
    close file
    
    Important: Use append mode for adding new student records. If write mode is used every time, old records may be overwritten.

    Assignment Task 6: Add Header Row

    A CSV file should have a header row so that the columns are easy to understand. However, the header should not be added repeatedly before every record.

    The header row should look like this:

    
    rollNumber,name,course,marks,grade,status
    

    The program should add this header only when the file is created for the first time or when the file is empty.

    
    // Conceptual header logic
    
    if file does not exist or file is empty
        write header row
    
    append student record
    

    Assignment Task 7: Read and Display Saved Records

    After saving student records, the program should be able to read the file and display all saved records.

    
    // Conceptual read logic
    
    open "data/students.csv" in read mode
    
    for each line in file
        display line
    
    close file
    

    Students can display the records as plain lines first. Later, they can improve formatting by splitting each CSV line into columns.

    Assignment Task 8: Create a Simple Menu

    As an optional improvement, create a menu-based program. The menu can allow users to choose what they want to do.

    
    // Conceptual menu
    
    1. Add Student Record
    2. View All Student Records
    3. Exit
    
    Enter your choice:
    

    This makes the program more interactive and practical.

    Suggested Program Flow

    The program should follow a clear flow from input to file saving.

    PROGRAM FLOW
    Input Validate Calculate Save Display
    
    Start Program
    
    Show Menu
    
    If user chooses Add Student:
        Accept student details
        Validate marks
        Calculate grade
        Calculate status
        Save record to file
        Show success message
    
    If user chooses View Records:
        Read records from file
        Display records
    
    If user chooses Exit:
        End Program
    

    Sample Input

    The program may accept input like this:

    
    Enter Roll Number: 101
    Enter Name: Rahul
    Enter Course: Programming Fundamentals
    Enter Marks: 85
    

    Sample Output

    After saving the record, the program may display:

    
    Student record saved successfully.
    

    If the user views all records, the output may look like this:

    
    rollNumber,name,course,marks,grade,status
    101,Rahul,Programming Fundamentals,85,B,Passed
    102,Ayesha,Programming Fundamentals,92,A,Passed
    103,John,Programming Fundamentals,35,Fail,Failed
    

    Expected File Content

    The final CSV file should look similar to this:

    
    rollNumber,name,course,marks,grade,status
    101,Rahul,Programming Fundamentals,85,B,Passed
    102,Ayesha,Programming Fundamentals,92,A,Passed
    103,John,Programming Fundamentals,35,Fail,Failed
    104,Priya,Programming Fundamentals,88,B,Passed
    

    Each student should appear on a new line. The column order should remain consistent.

    Language-Neutral Pseudocode Solution

    The following pseudocode gives a complete idea of the assignment logic. Students can convert this logic into any programming language.

    
    function calculateGrade(marks):
        if marks >= 90:
            return "A"
        else if marks >= 75:
            return "B"
        else if marks >= 60:
            return "C"
        else if marks >= 40:
            return "D"
        else:
            return "Fail"
    
    
    function calculateStatus(marks):
        if marks >= 40:
            return "Passed"
        else:
            return "Failed"
    
    
    function saveStudentRecord():
        input rollNumber
        input studentName
        input courseName
        input marks
    
        if marks < 0 or marks > 100:
            print "Invalid marks. Record not saved."
            return
    
        grade = calculateGrade(marks)
        status = calculateStatus(marks)
    
        filePath = "data/students.csv"
    
        if file does not exist or file is empty:
            write header row to file
    
        open file in append mode
    
        record = rollNumber + "," + studentName + "," + courseName + "," + marks + "," + grade + "," + status
    
        write record to file with newline
    
        close file
    
        print "Student record saved successfully."
    
    
    function viewStudentRecords():
        filePath = "data/students.csv"
    
        if file does not exist:
            print "No student records found."
            return
    
        open file in read mode
    
        for each line in file:
            print line
    
        close file
    
    
    start program
    
    repeat:
        print "1. Add Student Record"
        print "2. View Student Records"
        print "3. Exit"
    
        input choice
    
        if choice == 1:
            saveStudentRecord()
        else if choice == 2:
            viewStudentRecords()
        else if choice == 3:
            print "Program ended."
            stop
        else:
            print "Invalid choice."
    

    Optional Java-Style Sample Solution

    The following sample solution is written in Java-style syntax to help students understand one possible implementation. Students can implement the same logic in any language.

    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Scanner;
    
    public class StudentRecordSaver {
    
        static String filePath = "data/students.csv";
    
        static String calculateGrade(int marks) {
            if (marks >= 90) {
                return "A";
            } else if (marks >= 75) {
                return "B";
            } else if (marks >= 60) {
                return "C";
            } else if (marks >= 40) {
                return "D";
            } else {
                return "Fail";
            }
        }
    
        static String calculateStatus(int marks) {
            if (marks >= 40) {
                return "Passed";
            } else {
                return "Failed";
            }
        }
    
        static void saveStudentRecord() {
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter Roll Number: ");
            String rollNumber = scanner.nextLine();
    
            System.out.print("Enter Name: ");
            String name = scanner.nextLine();
    
            System.out.print("Enter Course: ");
            String course = scanner.nextLine();
    
            System.out.print("Enter Marks: ");
            int marks = scanner.nextInt();
    
            if (marks < 0 || marks > 100) {
                System.out.println("Invalid marks. Marks must be between 0 and 100.");
                return;
            }
    
            String grade = calculateGrade(marks);
            String status = calculateStatus(marks);
    
            try {
                File folder = new File("data");
    
                if (!folder.exists()) {
                    folder.mkdir();
                }
    
                File file = new File(filePath);
                boolean isNewFile = !file.exists() || file.length() == 0;
    
                FileWriter writer = new FileWriter(filePath, true);
    
                if (isNewFile) {
                    writer.write("rollNumber,name,course,marks,grade,status\n");
                }
    
                writer.write(rollNumber + "," + name + "," + course + "," + marks + "," + grade + "," + status + "\n");
    
                writer.close();
    
                System.out.println("Student record saved successfully.");
    
            } catch (IOException error) {
                System.out.println("Error saving student record: " + error.getMessage());
            }
        }
    
        static void viewStudentRecords() {
            try {
                File file = new File(filePath);
    
                if (!file.exists()) {
                    System.out.println("No student records found.");
                    return;
                }
    
                BufferedReader reader = new BufferedReader(new FileReader(filePath));
    
                String line;
    
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
    
                reader.close();
    
            } catch (IOException error) {
                System.out.println("Error reading student records: " + error.getMessage());
            }
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            while (true) {
                System.out.println("===== Student Record Saver =====");
                System.out.println("1. Add Student Record");
                System.out.println("2. View Student Records");
                System.out.println("3. Exit");
                System.out.print("Enter your choice: ");
    
                int choice = scanner.nextInt();
    
                if (choice == 1) {
                    saveStudentRecord();
                } else if (choice == 2) {
                    viewStudentRecords();
                } else if (choice == 3) {
                    System.out.println("Program ended.");
                    break;
                } else {
                    System.out.println("Invalid choice.");
                }
            }
        }
    }
    

    Concepts Applied in This Assignment

    The following table shows which programming concepts are practiced in this assignment.

    Concept Where It Is Used Purpose
    Variables rollNumber, name, course, marks Stores student details temporarily.
    Input Accepting student details Gets data from the user.
    Conditional Statements Grade calculation and validation Makes decisions based on marks.
    Functions / Methods calculateGrade(), saveStudentRecord() Organizes logic into reusable blocks.
    File Writing Creating students.csv Saves data into a file.
    File Appending Adding new student records Preserves old records and adds new ones.
    File Reading Viewing all records Reads saved data from the file.
    File Paths data/students.csv Defines where the file is stored.
    CSV Student record format Stores table-like records.
    Exception Handling File read/write errors Handles file problems safely.

    Extension Tasks

    After completing the basic assignment, students can improve the project by adding more features.

    Optional Enhancements

    • Search student by roll number.
    • Count total number of saved student records.
    • Display only passed students.
    • Display only failed students.
    • Calculate average marks of all students.
    • Find the student with highest marks.
    • Prevent duplicate roll numbers.
    • Save records in JSON format.
    • Export student report to a separate file.
    • Add date and time when each record is saved.
    • Add a delete record feature.
    • Add an update marks feature.

    Evaluation Criteria

    The assignment can be evaluated using the following criteria.

    Criteria Marks What to Check
    Input Handling 10 Student details are accepted properly.
    Validation 15 Marks are validated correctly.
    Grade Calculation 15 Grade and status are calculated correctly.
    File Writing / Appending 20 Student records are saved without deleting old records.
    File Reading 15 Saved records can be displayed correctly.
    CSV Format 10 Records follow a consistent CSV structure.
    Error Handling 10 File errors are handled with clear messages.
    Code Readability 5 Code is clean and easy to understand.
    Total 100 Complete file-based student record saver.

    Common Mistakes to Avoid

    Students should avoid the following mistakes while completing this assignment.

    Mistakes

    • Using write mode instead of append mode for new records.
    • Overwriting old student records accidentally.
    • Forgetting to add newline after each record.
    • Saving marks without validation.
    • Not adding a CSV header row.
    • Adding the header row repeatedly before every record.
    • Using inconsistent column order.
    • Not closing the file after writing.
    • Ignoring file path errors.
    • Not handling file reading or writing exceptions.

    Correct Approach

    • Use append mode when adding new records.
    • Use write mode only when creating or resetting a file intentionally.
    • Add newline after every record.
    • Validate marks before saving.
    • Add the header row only once.
    • Keep CSV column order consistent.
    • Use clear file paths such as data/students.csv.
    • Close files properly after operations.
    • Use exception handling for file errors.
    • Test with multiple student records.

    Best Practices

    Follow these best practices to create a clean and reliable solution.

    Recommended Practices

    • Use a separate folder for data files.
    • Use a meaningful file name such as students.csv.
    • Use append mode for adding records.
    • Use a header row in CSV files.
    • Validate data before saving it.
    • Use functions or methods for reusable logic.
    • Keep grade calculation separate from file writing logic.
    • Use exception handling for file operations.
    • Show clear success and error messages.
    • Test the program with valid and invalid marks.
    • Test whether old records remain after adding new records.
    • Keep file format consistent for easy reading later.

    Frequently Asked Questions

    1. What is the main goal of this assignment?

    The main goal is to practice saving student records permanently in a file using file handling concepts.

    2. Which file format is recommended for this assignment?

    CSV is recommended because student records are table-like data with rows and columns.

    3. Why should append mode be used?

    Append mode should be used so that new student records are added without deleting old records.

    4. What happens if write mode is used every time?

    If write mode is used every time, old records may be overwritten and lost.

    5. Why is marks validation important?

    Marks validation prevents invalid data such as -5 or 120 from being saved into the file.

    6. Why should the CSV header be added?

    The CSV header explains what each column means, making the file easier to understand and process.

    7. Should the header be added before every record?

    No. The header should usually be added only once, when the file is created or empty.

    8. Can this assignment be done in any programming language?

    Yes. The same logic can be implemented in any language that supports file handling, such as Java, Python, JavaScript, C#, PHP, C++, or Ruby.

    9. Can JSON be used instead of CSV?

    Yes. JSON can be used as an extension task, especially if the student record contains nested data.

    10. What should students submit?

    Students should submit source code, sample input, sample output, generated file content, and a short explanation of how file reading, writing, and appending are used.

    Assignment Summary

    This assignment helps students practice saving student records in a file. It connects several file handling topics such as writing files, appending files, reading files, file paths, CSV format, validation, and error handling.

    Students should create a program that accepts student details, validates marks, calculates grade and status, and saves the record into a CSV file. The program should use append mode so that old records are preserved and new records are added safely.

    This assignment prepares students for more advanced data storage concepts such as database tables, CRUD operations, and real-world record management systems.

    Key Takeaway

    The Save Student Records in a File assignment teaches how to store data permanently using file handling. Students practice collecting input, validating data, calculating grade, saving records in CSV format, appending new records, reading saved data, and handling file errors safely.