Programming Fundamentals
Assignment # 02
Submission instructions:
Students are required to complete the assignment and submit it by the due date. Make
sure the solutions are well-documented with proper comments in your C code.
Last Date of Submission: 22nd August 2025
Mode of Submission: Submit a soft copy (Word or PDF file) along with C source code
files.
Note: Late submissions may not be accepted or may incur grade penalties.
1. Static and Dynamic Memory Allocation
In C programming, memory allocation can be handled in two ways: static and dynamic.
• Static Memory Allocation: Memory for variables is allocated at compile time. The size and
type of variables must be known before the program runs. Example: declaring arrays with
fixed size.
• Dynamic Memory Allocation: Memory is allocated at runtime using functions like malloc(),
calloc(), realloc(), and free(). This provides flexibility to handle data of varying sizes.
Example in C:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Static Memory Allocation
int staticArr[5] = {1, 2, 3, 4, 5};
printf("Static Array Elements: ");
for(int i=0; i<5; i++) {
printf("%d ", staticArr[i]);
}
// Dynamic Memory Allocation
int *dynamicArr;
dynamicArr = (int*) malloc(5 * sizeof(int));
for(int i=0; i<5; i++) {
dynamicArr[i] = i+1;
}
printf("\nDynamic Array Elements: ");
for(int i=0; i<5; i++) {
printf("%d ", dynamicArr[i]);
}
free(dynamicArr);
return 0;
}
Assignment Question:
Write a C program for a library system where you need to store the number of books
borrowed by students. Use static memory allocation if the maximum number of students is
fixed (e.g., 50 students). Then implement the same program using dynamic memory
allocation to allow flexible handling of varying numbers of students.
2. File Input/Output Operations
File handling in C allows programs to read from and write to files, enabling permanent
storage of data. Common functions used in file operations include fopen(), fclose(), fprintf(),
fscanf(), fputs(), fgets(), fread(), fwrite(), etc.
Example in C:
#include <stdio.h>
int main() {
FILE *fptr;
char data[100];
// Writing to a file
fptr = fopen("[Link]", "w");
if(fptr == NULL) {
printf("Error! File not opened.");
return 1;
}
fprintf(fptr, "This is a test file.\n");
fclose(fptr);
// Reading from a file
fptr = fopen("[Link]", "r");
if(fptr == NULL) {
printf("Error! File not opened.");
return 1;
}
while(fgets(data, 100, fptr)) {
printf("%s", data);
}
fclose(fptr);
return 0;
}
Assignment Question:
Write a C program for a student grading system that stores student names and their grades
into a file. Then, read the file and display the list of students along with their grades.