logo

Long Answer Questions (8 Marks Each) (Part 2)

26. Write a C program to create a student database where each student record contains roll_no, name, and marks. The program

should allow adding, modifying, and deleting student records.

Solution:

c
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Student { int roll_no; char name[50]; float marks; }; void addRecord(FILE *file) { struct Student student; printf("Enter roll number: "); scanf("%d", &student.roll_no); printf("Enter name: "); getchar(); // To consume the newline character left by scanf fgets(student.name, sizeof(student.name), stdin); student.name[strcspn(student.name, "\n")] = '\0'; // Remove newline character printf("Enter marks: "); scanf("%f", &student.marks); fwrite(&student, sizeof(struct Student), 1, file); printf("Record added successfully.\n"); } void readRecords(FILE *file) { struct Student student; fseek(file, 0, SEEK_SET); while (fread(&student, sizeof(struct Student), 1, file)) { printf("Roll No: %d, Name: %s, Marks: %.2f\n", student.roll_no, student.name, student.marks); } } void deleteRecord(FILE *file) { struct Student student; int roll_no, found = 0; FILE *tempFile = fopen("temp.dat", "wb"); printf("Enter roll number to delete: "); scanf("%d", &roll_no); fseek(file, 0, SEEK_SET); while (fread(&student, sizeof(struct Student), 1, file)) { if (student.roll_no == roll_no) { found = 1; continue; // Skip the record to delete it } fwrite(&student, sizeof(struct Student), 1, tempFile); } fclose(file); fclose(tempFile); remove("students.dat"); rename("temp.dat", "students.dat"); if (found) printf("Record deleted successfully.\n"); else printf("Record not found.\n"); } int main() { FILE *file = fopen("students.dat", "ab+"); if (file == NULL) { printf("Error opening file.\n"); return 1; } int choice; do { printf("\nMenu:\n"); printf("1. Add Record\n"); printf("2. Read Records\n"); printf("3. Delete Record\n"); printf("4. Quit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: addRecord(file); break; case 2: readRecords(file); break; case 3: deleteRecord(file); break; case 4: printf("Exiting...\n"); break; default: printf("Invalid choice. Try again.\n"); } } while (choice != 4); fclose(file); return 0; }

27. Write a C program to implement a menu-based system where users can:

  • Append a record

  • Read a record

  • Delete a record

  • Quit the program

    Solution: The solution is the same as in question 26, as the program already implements a menu-based system to append, read, and delete records.


28. Write a C program to input the names, roll numbers, and marks of 10 students, store them in a file, and display the stored data.

Solution:

c
#include <stdio.h> struct Student { int roll_no; char name[50]; float marks; }; int main() { FILE *file = fopen("students.txt", "wb"); if (file == NULL) { printf("Error opening file.\n"); return 1; } struct Student students[10]; for (int i = 0; i < 10; i++) { printf("Enter roll number for student %d: ", i + 1); scanf("%d", &students[i].roll_no); printf("Enter name for student %d: ", i + 1); getchar(); // To consume newline fgets(students[i].name, sizeof(students[i].name), stdin); students[i].name[strcspn(students[i].name, "\n")] = '\0'; // Remove newline printf("Enter marks for student %d: ", i + 1); scanf("%f", &students[i].marks); } fwrite(students, sizeof(struct Student), 10, file); fclose(file); // Display stored data file = fopen("students.txt", "rb"); if (file == NULL) { printf("Error opening file.\n"); return 1; } printf("\nStored student data:\n"); for (int i = 0; i < 10; i++) { fread(&students[i], sizeof(struct Student), 1, file); printf("Roll No: %d, Name: %s, Marks: %.2f\n", students[i].roll_no, students[i].name, students[i].marks); } fclose(file); return 0; }

29. Explain the file handling concept in C. Write a program to read and display data from a file named data.txt.

Explanation: File handling in C is a mechanism used to store data in a file and retrieve data from it. It includes functions like:

  • fopen(): Opens a file.
  • fclose(): Closes a file.
  • fread(): Reads data from a file.
  • fwrite(): Writes data to a file.
  • fprintf(): Writes formatted data to a file.
  • fscanf(): Reads formatted data from a file.

Solution:

c
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "r"); if (file == NULL) { printf("Error opening file.\n"); return 1; } char ch; while ((ch = fgetc(file)) != EOF) { putchar(ch); // Display the file content } fclose(file); return 0; }

30. Explain the concept of recursion in C. Write a recursive function to print the Fibonacci series up to n terms.

Explanation: Recursion is a technique where a function calls itself to solve a problem. In the Fibonacci sequence, the nth term is the sum of the (n-1)th and (n-2)th terms. Recursion naturally fits this problem.

Solution:

c
#include <stdio.h> int fibonacci(int n) { if (n <= 1) return n; else return fibonacci(n - 1) + fibonacci(n - 2); } int main() { int n; printf("Enter the number of terms: "); scanf("%d", &n); printf("Fibonacci Series: "); for (int i = 0; i < n; i++) { printf("%d ", fibonacci(i)); } return 0; }

31. Differentiate between function and pointer in C. Write a program to use a pointer to store and display the values of an array.

Explanation:

  • A function is a block of code designed to perform a particular task.
  • A pointer is a variable that stores the memory address of another variable. Pointers are commonly used for dynamic memory allocation and for referencing arrays, structures, etc.

Solution:

c
#include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; int *ptr = arr; // Pointer to the array printf("Array elements using pointer:\n"); for (int i = 0; i < 5; i++) { printf("Element %d: %d\n", i + 1, *(ptr + i)); // Dereferencing the pointer } return 0; }

32. Write a C program to open a file, read student records (name, roll number, and marks), and display them on the screen.

c
#include <stdio.h> struct Student { char name[50]; int roll_no; float marks; }; int main() { FILE *file; struct Student student; file = fopen("students.txt", "r"); if (file == NULL) { printf("Unable to open file\n"); return 1; } while (fscanf(file, "%s %d %f", student.name, &student.roll_no, &student.marks) != EOF) { printf("Name: %s, Roll No: %d, Marks: %.2f\n", student.name, student.roll_no, student.marks); } fclose(file); return 0; }

33. Describe the importance of structure in C. Write a program to store and display details of 10 employees (ID, name, salary) using structures.

Importance of Structures in C: Structures in C allow you to group different types of data under a single name. It helps in organizing related data together, making the code more readable and easier to manage.

c
#include <stdio.h> struct Employee { int id; char name[50]; float salary; }; int main() { struct Employee employees[10]; for (int i = 0; i < 10; i++) { printf("Enter ID, Name and Salary for employee %d: ", i + 1); scanf("%d %s %f", &employees[i].id, employees[i].name, &employees[i].salary); } printf("\nEmployee Details:\n"); for (int i = 0; i < 10; i++) { printf("ID: %d, Name: %s, Salary: %.2f\n", employees[i].id, employees[i].name, employees[i].salary); } return 0; }

34. Write a C program to create an employee management system that allows users to add, update, delete, and display employee records stored in a file.

c
#include <stdio.h> #include <string.h> struct Employee { int id; char name[50]; float salary; }; void addEmployee(FILE *file) { struct Employee employee; printf("Enter ID, Name and Salary: "); scanf("%d %s %f", &employee.id, employee.name, &employee.salary); fprintf(file, "%d %s %.2f\n", employee.id, employee.name, employee.salary); } void displayEmployees(FILE *file) { struct Employee employee; while (fscanf(file, "%d %s %f", &employee.id, employee.name, &employee.salary) != EOF) { printf("ID: %d, Name: %s, Salary: %.2f\n", employee.id, employee.name, employee.salary); } } int main() { FILE *file; int choice; file = fopen("employees.txt", "a+"); if (file == NULL) { printf("Unable to open file\n"); return 1; } do { printf("\n1. Add Employee\n2. Display Employees\n3. Exit\nEnter choice: "); scanf("%d", &choice); switch (choice) { case 1: addEmployee(file); break; case 2: displayEmployees(file); break; case 3: printf("Exiting...\n"); break; default: printf("Invalid choice!\n"); } } while (choice != 3); fclose(file); return 0; }

35. Explain the importance of pointers in dynamic memory allocation. Write a C program to allocate memory dynamically for an array and display its elements.

Importance of Pointers in Dynamic Memory Allocation: Pointers are crucial for dynamic memory allocation as they allow for the efficient use of memory during program execution. With dynamic memory, memory can be allocated at runtime, and its size can be determined by user input.

c
#include <stdio.h> #include <stdlib.h> int main() { int *arr, n; printf("Enter the number of elements: "); scanf("%d", &n); // Dynamically allocate memory arr = (int*)malloc(n * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed\n"); return 1; } // Input elements for (int i = 0; i < n; i++) { printf("Enter element %d: ", i + 1); scanf("%d", &arr[i]); } // Display elements printf("Entered elements are:\n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } // Free the allocated memory free(arr); return 0; }

36. Write a C program to demonstrate file handling operations (read, write, append) on a text file named data.txt.

c
#include <stdio.h> int main() { FILE *file; // Write to file file = fopen("data.txt", "w"); if (file == NULL) { printf("Unable to open file for writing\n"); return 1; } fprintf(file, "Hello, this is a test file.\n"); fclose(file); // Append to file file = fopen("data.txt", "a"); if (file == NULL) { printf("Unable to open file for appending\n"); return 1; } fprintf(file, "Appending new content.\n"); fclose(file); // Read from file file = fopen("data.txt", "r"); if (file == NULL) { printf("Unable to open file for reading\n"); return 1; } char line[100]; while (fgets(line, sizeof(line), file)) { printf("%s", line); } fclose(file); return 0; }

37. Explain the use of command-line arguments in C. Write a program to read a file name from the command line and display its content.

Command-line arguments in C: Command-line arguments provide a way to pass input to a program when it is executed from the command line. These arguments are stored in argv[] and the number of arguments in argc.

c
#include <stdio.h> int main(int argc, char *argv[]) { FILE *file; char ch; if (argc != 2) { printf("Usage: %s <filename>\n", argv[0]); return 1; } file = fopen(argv[1], "r"); if (file == NULL) { printf("Unable to open file %s\n", argv[1]); return 1; } while ((ch = fgetc(file)) != EOF) { putchar(ch); } fclose(file); return 0; }

38. Describe the concept of call by value and call by reference in C. Write a program to swap two numbers using both approaches.

Call by Value: In call by value, a copy of the actual parameter is passed to the function. Any changes made to the parameter inside the function do not affect the original value.

Call by Reference: In call by reference, the address of the actual parameter is passed to the function. Any changes made to the parameter inside the function will reflect in the original value.

c
#include <stdio.h> // Call by value void swapByValue(int a, int b) { int temp = a; a = b; b = temp; } // Call by reference void swapByReference(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int main() { int x = 5, y = 10; printf("Before swap (by value): x = %d, y = %d\n", x, y); swapByValue(x, y); printf("After swap (by value): x = %d, y = %d\n", x, y); printf("Before swap (by reference): x = %d, y = %d\n", x, y); swapByReference(&x, &y); printf("After swap (by reference): x = %d, y = %d\n", x, y); return 0; }

39. Write a C program to demonstrate the difference between structure and union using an example.

c
#include <stdio.h> struct ExampleStruct { int i; float f; }; union ExampleUnion { int i; float f; }; int main() { struct ExampleStruct s; union ExampleUnion u; s.i = 5; s.f = 10.5; u.i = 5; u.f = 10.5; printf("Structure - Integer: %d, Float: %.2f\n", s.i, s.f); printf("Union - Integer: %d, Float: %.2f\n", u.i, u.f); return 0; }

40. Explain the different storage classes in C (auto, register, static, and extern) with suitable examples.

Storage classes in C:

  • auto: Default storage class for local variables. Variables are created when the function is called and destroyed when the function returns.
  • register: Suggests that the variable be stored in a CPU register for faster access.
  • static: The variable retains its value between function calls.
  • extern: Used to declare a variable defined in another file.
c
#include <stdio.h> extern int externVar; int main() { auto int autoVar = 5; // Default local variable register int regVar = 10; // Stored in register static int staticVar = 15; // Retains value across function calls printf("Auto variable: %d\n", autoVar); printf("Register variable: %d\n", regVar); printf("Static variable: %d\n", staticVar); return 0; }

41. Write a C program to read the marks of 5 students in a subject and count how many students passed and failed (pass marks = 35).

c
#include <stdio.h> int main() { int marks[5], passCount = 0, failCount = 0; for (int i = 0; i < 5; i++) { printf("Enter marks for student %d: ", i + 1); scanf("%d", &marks[i]); if (marks[i] >= 35) passCount++; else failCount++; } printf("\nPassed: %d, Failed: %d\n", passCount, failCount); return 0; }

42. Write a program to calculate the sum, average, and highest marks of students in a class using an array of structures.

c
#include <stdio.h> struct Student { int marks; }; int main() { struct Student students[5]; int totalMarks = 0, highestMarks = 0; for (int i = 0; i < 5; i++) { printf("Enter marks for student %d: ", i + 1); scanf("%d", &students[i].marks); totalMarks += students[i].marks; if (students[i].marks > highestMarks) highestMarks = students[i].marks; } printf("Total Marks: %d\n", totalMarks); printf("Average Marks: %.2f\n", totalMarks / 5.0); printf("Highest Marks: %d\n", highestMarks); return 0; }

43. Explain the working of fprintf() and fscanf() functions in file handling. Write a program to write and read student records from a file.

c
#include <stdio.h> struct Student { char name[50]; int roll_no; float marks; }; int main() { FILE *file; struct Student student = {"John Doe", 101, 95.5}; file = fopen("students.txt", "w"); if (file == NULL) { printf("Unable to open file for writing\n"); return 1; } fprintf(file, "%s %d %.2f\n", student.name, student.roll_no, student.marks); fclose(file); file = fopen("students.txt", "r"); if (file == NULL) { printf("Unable to open file for reading\n"); return 1; } fscanf(file, "%s %d %f", student.name, &student.roll_no, &student.marks); printf("Name: %s, Roll No: %d, Marks: %.2f\n", student.name, student.roll_no, student.marks); fclose(file); return 0; }

44. Write a C program to create a library management system that stores book details (title, author, price) in a file and allows users to search for books.

c
#include <stdio.h> #include <string.h> struct Book { char title[50]; char author[50]; float price; }; void addBook(FILE *file) { struct Book book; printf("Enter book title: "); scanf("%s", book.title); printf("Enter book author: "); scanf("%s", book.author); printf("Enter book price: "); scanf("%f", &book.price); fprintf(file, "%s %s %.2f\n", book.title, book.author, book.price); } void searchBook(FILE *file, char *searchTitle) { struct Book book; int found = 0; while (fscanf(file, "%s %s %f", book.title, book.author, &book.price) != EOF) { if (strcmp(book.title, searchTitle) == 0) { printf("Book found: Title: %s, Author: %s, Price: %.2f\n", book.title, book.author, book.price); found = 1; break; } } if (!found) { printf("Book not found.\n"); } } int main() { FILE *file; char searchTitle[50]; int choice; file = fopen("library.txt", "a+"); if (file == NULL) { printf("Unable to open file\n"); return 1; } do { printf("\n1. Add Book\n2. Search Book\n3. Exit\nEnter choice: "); scanf("%d", &choice); switch (choice) { case 1: addBook(file); break; case 2: printf("Enter title of the book to search: "); scanf("%s", searchTitle); searchBook(file, searchTitle); break; case 3: printf("Exiting...\n"); break; default: printf("Invalid choice!\n"); } } while (choice != 3); fclose(file); return 0; }

45. Explain how linked lists work in C. Write a C program to implement a simple singly linked list with insertion and deletion operations.

Explanation of Linked Lists in C: A linked list is a data structure where each element (node) contains data and a pointer to the next node in the sequence. This allows for efficient insertion and deletion of elements.

c
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void insert(struct Node **head, int data) { struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = *head; *head = newNode; } void delete(struct Node **head, int data) { struct Node *temp = *head, *prev = NULL; if (temp != NULL && temp->data == data) { *head = temp->next; free(temp); return; } while (temp != NULL && temp->data != data) { prev = temp; temp = temp->next; } if (temp == NULL) return; prev->next = temp->next; free(temp); } void display(struct Node *head) { struct Node *temp = head; while (temp != NULL) { printf("%d -> ", temp->data); temp = temp->next; } printf("NULL\n"); } int main() { struct Node *head = NULL; insert(&head, 10); insert(&head, 20); insert(&head, 30); printf("Linked list: "); display(head); delete(&head, 20); printf("Linked list after deletion: "); display(head); return 0; }

46. Write a program to perform matrix multiplication using two-dimensional arrays in C.

Solution:

c
#include <stdio.h> int main() { int row1, col1, row2, col2; // Input for first matrix dimensions printf("Enter the number of rows and columns for the first matrix: "); scanf("%d %d", &row1, &col1); // Input for second matrix dimensions printf("Enter the number of rows and columns for the second matrix: "); scanf("%d %d", &row2, &col2); // Check if multiplication is possible if (col1 != row2) { printf("Matrix multiplication is not possible.\n"); return 1; // End the program if multiplication is not possible } // Declare matrices int matrix1[row1][col1], matrix2[row2][col2], result[row1][col2]; // Input elements for first matrix printf("Enter elements of the first matrix:\n"); for (int i = 0; i < row1; i++) { for (int j = 0; j < col1; j++) { scanf("%d", &matrix1[i][j]); } } // Input elements for second matrix printf("Enter elements of the second matrix:\n"); for (int i = 0; i < row2; i++) { for (int j = 0; j < col2; j++) { scanf("%d", &matrix2[i][j]); } } // Initialize the result matrix with 0 for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) { result[i][j] = 0; } } // Perform matrix multiplication for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) { for (int k = 0; k < col1; k++) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } // Display the result matrix printf("The result of matrix multiplication is:\n"); for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) { printf("%d ", result[i][j]); } printf("\n"); } return 0; }

Explanation of the program:

  1. Input Dimensions: The program first takes the number of rows and columns for both matrices.
  2. Matrix Multiplication Condition: For matrix multiplication to be possible, the number of columns in the first matrix should be equal to the number of rows in the second matrix. The program checks this condition.
  3. Input Matrices: The elements for both matrices are entered by the user.
  4. Matrix Multiplication Logic: The program uses three nested loops to multiply the corresponding elements of the matrices.
    • The outer two loops iterate through the rows and columns of the result matrix.
    • The innermost loop performs the multiplication and accumulation of the products.
  5. Display Result: The result matrix is printed to the console.

Sample Input:

sql
Enter the number of rows and columns for the first matrix: 2 3 Enter the number of rows and columns for the second matrix: 3 2 Enter elements of the first matrix: 1 2 3 4 5 6 Enter elements of the second matrix: 7 8 9 10 11 12

Sample Output:

The result of matrix multiplication is: 58 64 139 154

47. Write a C program to create a library management system that stores book details (title, author, price) in a file and allows users to search for books.

c
#include <stdio.h> #include <string.h> struct Book { char title[100]; char author[50]; float price; }; void searchBook(FILE *file, char *searchTitle) { struct Book book; int found = 0; while (fread(&book, sizeof(struct Book), 1, file)) { if (strcmp(book.title, searchTitle) == 0) { printf("Book Found: %s by %s, Price: %.2f\n", book.title, book.author, book.price); found = 1; break; } } if (!found) { printf("Book not found\n"); } } int main() { FILE *file = fopen("library.dat", "r+"); if (!file) { printf("Could not open file\n"); return 1; } char searchTitle[100]; printf("Enter the book title to search: "); gets(searchTitle); // Insecure, replace with safer input methods in production searchBook(file, searchTitle); fclose(file); return 0; }

48. Explain how linked lists work in C. Write a C program to implement a simple singly linked list with insertion and deletion operations.

c
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void insertAtEnd(struct Node **head, int value) { struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); struct Node *temp = *head; newNode->data = value; newNode->next = NULL; if (*head == NULL) { *head = newNode; return; } while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; } void deleteNode(struct Node **head, int value) { struct Node *temp = *head, *prev = NULL; if (temp != NULL && temp->data == value) { *head = temp->next; free(temp); return; } while (temp != NULL && temp->data != value) { prev = temp; temp = temp->next; } if (temp == NULL) { printf("Node not found\n"); return; } prev->next = temp->next; free(temp); } void displayList(struct Node *head) { struct Node *temp = head; while (temp != NULL) { printf("%d -> ", temp->data); temp = temp->next; } printf("NULL\n"); } int main() { struct Node *head = NULL; insertAtEnd(&head, 10); insertAtEnd(&head, 20); insertAtEnd(&head, 30); printf("List: "); displayList(head); deleteNode(&head, 20); printf("List after deletion: "); displayList(head); return 0; }

49. Write a program to perform matrix multiplication using two-dimensional arrays in C.

c
#include <stdio.h> #define MAX 10 void multiplyMatrices(int first[MAX][MAX], int second[MAX][MAX], int result[MAX][MAX], int rowFirst, int colFirst, int rowSecond, int colSecond) { for (int i = 0; i < rowFirst; i++) { for (int j = 0; j < colSecond; j++) { result[i][j] = 0; for (int k = 0; k < colFirst; k++) { result[i][j] += first[i][k] * second[k][j]; } } } } int main() { int first[MAX][MAX], second[MAX][MAX], result[MAX][MAX]; int rowFirst, colFirst, rowSecond, colSecond; printf("Enter rows and columns for the first matrix: "); scanf("%d %d", &rowFirst, &colFirst); printf("Enter rows and columns for the second matrix: "); scanf("%d %d", &rowSecond, &colSecond); if (colFirst != rowSecond) { printf("Matrix multiplication not possible.\n"); return 1; } printf("Enter elements of first matrix:\n"); for (int i = 0; i < rowFirst; i++) { for (int j = 0; j < colFirst; j++) { scanf("%d", &first[i][j]); } } printf("Enter elements of second matrix:\n"); for (int i = 0; i < rowSecond; i++) { for (int j = 0; j < colSecond; j++) { scanf("%d", &second[i][j]); } } multiplyMatrices(first, second, result, rowFirst, colFirst, rowSecond, colSecond); printf("Resultant Matrix:\n"); for (int i = 0; i < rowFirst; i++) { for (int j = 0; j < colSecond; j++) { printf("%d ", result[i][j]); } printf("\n"); } return 0; }

50. Describe the working of recursive functions in C. Write a recursive function to calculate the GCD (Greatest Common Divisor) of two numbers.

c
#include <stdio.h> int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int num1, num2; printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); printf("The GCD of %d and %d is: %d\n", num1, num2, gcd(num1, num2)); return 0; }

Discussion (20)