DOEACC
[M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH ‘C’ LANGUAGE]
Q. Write a C program to construct a linear linked list in C to store student records. The record contains roll no. and total marks. The program stops when a negative roll no. is entered.
#include <stdio.h>
#include <stdlib.h>
// Structure to represent a student record
struct Student {
int rollNo;
float totalMarks;
struct Student* next;
};
// Function to insert a new student record at the end of the linked list
struct Student* insertRecord(struct Student* head, int rollNo, float totalMarks) {
struct Student* newStudent = (struct Student*)malloc(sizeof(struct Student));
newStudent->rollNo = rollNo;
newStudent->totalMarks = totalMarks;
newStudent->next = NULL;
if (head == NULL) {
// If the list is empty, the new student becomes the head
head = newStudent;
} else {
// Traverse the list to find the last node and append the new student
struct Student* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newStudent;
}
return head;
}
// Function to display the student records
void displayRecords(struct Student* head) {
printf("Student Records:\n");
printf("Roll No\tTotal Marks\n");
struct Student* temp = head;
while (temp != NULL) {
printf("%d\t%.2f\n", temp->rollNo, temp->totalMarks);
temp = temp->next;
}
}
// Function to free the memory allocated for the linked list
void freeList(struct Student* head) {
struct Student* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
int main() {
struct Student* head = NULL;
int rollNo;
float totalMarks;
// Input student records until a negative roll number is entered
while (1) {
printf("Enter roll number (negative to stop): ");
scanf("%d", &rollNo);
// Check if the entered roll number is negative
if (rollNo < 0) {
break;
}
printf("Enter total marks: ");
scanf("%f", &totalMarks);
// Insert the student record into the linked list
head = insertRecord(head, rollNo, totalMarks);
}
// Display the student records
displayRecords(head);
// Free the memory allocated for the linked list
freeList(head);
return 0;
}
No comments:
Post a Comment