0% found this document useful (0 votes)
11 views

Struct Point Files

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Struct Point Files

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UCS2201 Fundamentals and Practice of Software Development

A7: Programs using Structures, Pointers and Files

Batch 2023-202 Academic Year 2023-2024 Even

Assignment:
1. Define a datatype for Employee with members Emp_Id,
Emp_Name, DOB, Age, Address, Dept, Basic_Salary,
Allowance[3], Deduction[2], Gross_Salary and Net_Salary.
Define DOB with members namely Day, Month and Year. Define
Address with membersnamely Door_No, Street, Area, City and
Pincode. Let the Allowance array consists of
Dearness_Allowance, HRA and Medical_Allowance. The
Deduction array consists of PFand Income_Tax. Write a C
program using structures to perform the following operations.
a. Write a function to create an employee database using an
array of structures with5 employees belonging to 2
departments by passing the structure name and number of
employees as arguments to the functions. Get the input from
users onlyfor Emp_Id, Emp_Name, DOB, Address, Dept
and Basic_Salary.
b. Write a function to find the Age of an employee using DOB
and the current Dateby passing DOB as argument.
c. Write a function for calculating Allowances using the
following
i. Dearness_Allowance = 42% of Basic_Salary
ii. HRA = 10% of Basic_Salary
iii. Medical_Allowance = 15% of Basic_Salary
d. Write a function for calculating the Gross_Salary as
Basic_Salary + Allowances
e. Write a function for calculating Deductions using the
following
i. PF = 12% of Basic_Salary
ii. Income_Tax = 20% of Gross_Salary
f. Write a function for calculating the Net_Salary as
Basic_Salary + Allowances -
Deductions
g. Write a function to search for an employee based on the
Emp_Id and displayhis/her payslip.
h. Write a function to display the department that pays the
highest salary to an employee
CODE:
#include <stdio.h> #include
<stdlib.h> #include
<string.h>

// Define DOB structure


struct DateOfBirth {
int day; int
month; int
year;
};

// Define Address structure struct


Address {
char doorNo[20];
char street[50];
char area[50]; char
city[50];
int pincode;
};

// Define Employee structure


struct Employee {
int empId;
char empName[50];
struct DateOfBirth dob;
struct Address address;
char dept[20];
float basicSalary;
float allowance[3];
float deduction[2];
float grossSalary;
float netSalary;
};

// Function to calculate age based on date of birth


int calculateAge(struct DateOfBirth dob, int currentYear) { int
age = currentYear - dob.year;
if (dob.month > 6 || (dob.month == 6 && dob.day > 3)) //
Adjusting for the current month and day
age--;
return age;
}

// Function to calculate allowances


void calculateAllowances(struct Employee *emp) {
emp->allowance[0] = 0.42 * emp->basicSalary; // Dearness
Allowance
emp->allowance[1] = 0.10 * emp->basicSalary; // HRA
emp->allowance[2] = 0.15 * emp->basicSalary; // Medical
Allowance
}

// Function to calculate gross salary


void calculateGrossSalary(struct Employee *emp) {
emp->grossSalary = emp->basicSalary + emp->allowance[0]
+ emp->allowance[1] + emp->allowance[2];
}

// Function to calculate deductions


void calculateDeductions(struct Employee *emp) { emp-
>deduction[0] = 0.12 * emp->basicSalary; // PF
emp->deduction[1] = 0.20 * emp->grossSalary; // Income Tax
}

// Function to calculate net salary


void calculateNetSalary(struct Employee *emp) {
emp->netSalary = emp->grossSalary - emp->deduction[0] -
emp->deduction[1];
}

// Function to create employee database


void createEmployeeDatabase(struct Employee employees[], int
numEmployees) {
int i;
for (i = 0; i < numEmployees; i++) {
printf("Enter details for employee %d:\n", i + 1); printf("Employee ID:
");
scanf("%d", &employees[i].empId);
printf("Employee Name: "); scanf("%s",
employees[i].empName);
printf("Date of Birth (DD MM YYYY): ");
scanf("%d %d %d", &employees[i].dob.day,
&employees[i].dob.month, &employees[i].dob.year); printf("Address
(Door No, Street, Area, City, Pincode): "); scanf("%s %s %s %s
%d", employees[i].address.doorNo,
employees[i].address.street,
employees[i].address.area, employees[i].address.city,
&employees[i].address.pincode);
printf("Department: "); scanf("%s",
employees[i].dept); printf("Basic
Salary: ");
scanf("%f", &employees[i].basicSalary); printf("\n");
}
}

// Function to search for an employee based on Emp_Id and


display payslip
void searchEmployeeAndDisplayPayslip(struct Employee
employees[], int numEmployees, int empId) {
int i;
for (i = 0; i < numEmployees; i++) { if
(employees[i].empId == empId) {
printf("Employee ID: %d\n", employees[i].empId);
printf("Employee Name: %s\n",
employees[i].empName);
printf("Department: %s\n", employees[i].dept);
printf("Basic Salary: %.2f\n",
employees[i].basicSalary); printf("Dearness
Allowance: %.2f\n",
employees[i].allowance[0]);
printf("HRA: %.2f\n", employees[i].allowance[1]);
printf("Medical Allowance: %.2f\n",
employees[i].allowance[2]);
printf("Gross Salary: %.2f\n",
employees[i].grossSalary);
printf("PF: %.2f\n", employees[i].deduction[0]);
printf("Income Tax: %.2f\n",
employees[i].deduction[1]);
printf("Net Salary: %.2f\n", employees[i].netSalary);
return;
}
}
printf("Employee not found with ID %d\n", empId);
}

// Function to find the department paying the highest salary void


findDepartmentWithHighestSalary(struct Employee
employees[], int numEmployees) {
float maxSalary = 0;
char deptWithMaxSalary[20];
int i;
for (i = 0; i < numEmployees; i++) {
if (employees[i].grossSalary > maxSalary) {
maxSalary = employees[i].grossSalary;
strcpy(deptWithMaxSalary, employees[i].dept);
}
}
printf("Department with highest salary: %s\n",
deptWithMaxSalary);
}

int main() {
int currentYear = 2024; // Current year
struct Employee employees[5]; // Array of employees

// Create employee database


createEmployeeDatabase(employees, 5);

// Calculate age of each employee int


i;
for (i = 0; i < 5; i++) { employees[i].dob.year
= currentYear -
employees[i].dob.year;
}

// Calculate allowances, deductions, gross salary, and net


salary for each employee
for (i = 0; i < 5; i++) {
calculateAllowances(&employees[i]);
calculateGrossSalary(&employees[i]);
calculateDeductions(&employees[i]);
calculateNetSalary(&employees[i]);
}

// Search for an employee and display payslip


searchEmployeeAndDisplayPayslip(employees, 5, 1);

// Find the department with the highest salary


findDepartmentWithHighestSalary(employees, 5);

return 0;
}

SAMPLE OUTPUT:
2. Modify Qn 1 by using files to perform the following
a. Read the details namely Emp_Id, Emp_Name, DOB,
Address, Dept andBasic_Salary of 5 employees and store
them in a file.
b. Access the file sequentially to get the employee details for
computing Gross andNet salaries as mentioned in Qn 1.
c. Create 5 files consisting of the payslips of 5 employees.
CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Define DOB structure


struct DateOfBirth {
int day; int
month; int
year;
};

// Define Address structure


struct Address {
char doorNo[20];
char street[50];
char area[50]; char
city[50];
int pincode;
};

// Define Employee structure


struct Employee {
int empId;
char empName[50]; struct
DateOfBirth dob; struct
Address address; char
dept[20];
float basicSalary;
float allowance[3];
float deduction[2];
float grossSalary;
float netSalary;
};

// Function to calculate allowances


void calculateAllowances(struct Employee *emp) {
emp->allowance[0] = 0.42 * emp->basicSalary; // Dearness Allowance
emp->allowance[1] = 0.10 * emp->basicSalary; // HRA
emp->allowance[2] = 0.15 * emp->basicSalary; // Medical Allowance
}

// Function to calculate gross salary


void calculateGrossSalary(struct Employee *emp) {
emp->grossSalary = emp->basicSalary + emp->allowance[0] + emp-
>allowance[1] + emp->allowance[2];
}

// Function to calculate deductions


void calculateDeductions(struct Employee *emp) { emp-
>deduction[0] = 0.12 * emp->basicSalary; // PF
emp->deduction[1] = 0.20 * emp->grossSalary; // Income Tax
}

// Function to calculate net salary


void calculateNetSalary(struct Employee *emp) {
emp->netSalary = emp->grossSalary - emp->deduction[0] - emp-
>deduction[1];
}

// Function to create payslip file


void createPayslipFile(struct Employee *emp) { char
filename[50];
sprintf(filename, "payslip_%d.txt", emp->empId); FILE
*fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error opening file.\n");
return;
}
fprintf(fp, "Employee ID: %d\n", emp->empId); fprintf(fp,
"Employee Name: %s\n", emp->empName); fprintf(fp,
"Department: %s\n", emp->dept); fprintf(fp, "Basic Salary:
%.2f\n", emp->basicSalary);
fprintf(fp, "Dearness Allowance: %.2f\n", emp->allowance[0]); fprintf(fp,
"HRA: %.2f\n", emp->allowance[1]);
fprintf(fp, "Medical Allowance: %.2f\n", emp->allowance[2]);
fprintf(fp, "Gross Salary: %.2f\n", emp->grossSalary); fprintf(fp,
"PF: %.2f\n", emp->deduction[0]);
fprintf(fp, "Income Tax: %.2f\n", emp->deduction[1]);
fprintf(fp, "Net Salary: %.2f\n", emp->netSalary); fclose(fp);
}
int main() {
struct Employee employees[5]; // Array of employees
FILE *fp = fopen("employee_details.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
int i;
// Read employee details from file
for (i = 0; i < 5; i++) {
fscanf(fp, "%d", &employees[i].empId); fscanf(fp,
"%s", employees[i].empName); fscanf(fp, "%d %d
%d", &employees[i].dob.day,
&employees[i].dob.month, &employees[i].dob.year);
fscanf(fp, "%s %s %s %s %d", employees[i].address.doorNo,
employees[i].address.street,
employees[i].address.area, employees[i].address.city,
&employees[i].address.pincode);
fscanf(fp, "%s", employees[i].dept); fscanf(fp,
"%f", &employees[i].basicSalary);
}
fclose(fp);

// Calculate allowances, deductions, gross salary, and net salary for each employee
for (i = 0; i < 5; i++) {
calculateAllowances(&employees[i]);
calculateGrossSalary(&employees[i]);
calculateDeductions(&employees[i]);
calculateNetSalary(&employees[i]);
}

// Create payslip file for each employee


for (i = 0; i < 5; i++) {
createPayslipFile(&employees[i]);
}

printf("Payslip files created successfully.\n");

return 0;
}

SAMPLE OUTPUT:
3.Write a C program to input multiple lines of text and to determine the
number of vowels,consonants, digits, whitespace characters and other
characters for each line and finally tofind the average number of vowels per
line, consonants per line etc. Store the multiple lines of text whose maximum
length is unspecified. Maintain a pointer to each string within a one-
dimensional array of pointers.
CODE:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

// Function prototypes
void analyzeLine(char *line, int *vowels, int *consonants, int *digits, int
*whitespaces, int *others);

void calculateAverages(int totalLines, int totalVowels, int totalConsonants, int


totalDigits, int totalWhitespaces, int totalOthers);

int main() {
char **lines = NULL;
char buffer[1024];
int lineCount = 0;

printf("Enter lines of text (Press Enter on a blank line to stop):\n"); while (1)

{
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
break;
}

if (buffer[0] == '\n') {
break;
}

lines = realloc(lines, (lineCount + 1) * sizeof(char *));


lines[lineCount] = malloc((strlen(buffer) + 1) * sizeof(char));
strcpy(lines[lineCount], buffer);
lineCount++;
}

int totalVowels = 0, totalConsonants = 0, totalDigits = 0;


int totalWhitespaces = 0, totalOthers = 0;

for (int i = 0; i < lineCount; i++) {


int vowels = 0, consonants = 0, digits = 0;
int whitespaces = 0, others = 0;
analyzeLine(lines[i], &vowels, &consonants, &digits, &whitespaces,
&others);

totalVowels += vowels;
totalConsonants += consonants;
totalDigits += digits;
totalWhitespaces += whitespaces;
totalOthers += others;

printf("Line %d: Vowels=%d, Consonants=%d, Digits=%d,


Whitespaces=%d, Others=%d\n",
i + 1, vowels, consonants, digits, whitespaces, others);
}

if (lineCount > 0) {
calculateAverages(lineCount, totalVowels, totalConsonants, totalDigits,
totalWhitespaces, totalOthers);
}

// Free allocated memory


for (int i = 0; i < lineCount; i++) {
free(lines[i]);
}
free(lines);

return 0;
}

void analyzeLine(char *line, int *vowels, int *consonants, int *digits, int
*whitespaces, int *others) {
for (int i = 0; line[i] != '\0'; i++) { char
ch = line[i];
if (isalpha(ch)) {
if (strchr("AEIOUaeiou", ch)) {
(*vowels)++;
} else {
(*consonants)++;
}
} else if (isdigit(ch)) {
(*digits)++;
} else if (isspace(ch)) {
(*whitespaces)++;
} else {
(*others)++;
}
}
}

void calculateAverages(int totalLines, int totalVowels, int totalConsonants, int


totalDigits, int totalWhitespaces, int totalOthers) { printf("\nAverages per
line:\n");
printf("Vowels: %.2f\n", (float)totalVowels / totalLines);

printf("Consonants: %.2f\n", (float)totalConsonants / totalLines);


printf("Digits: %.2f\n", (float)totalDigits / totalLines); printf("Whitespaces:
%.2f\n", (float)totalWhitespaces / totalLines); printf("Others: %.2f\n",
(float)totalOthers / totalLines);
}

SAMPLE OUTPUT:
4.Write an interactive C program to maintain a list of names, addresses and
telephone numbers. Store the information as records in a file by representing
each record as a structure. Perform the following operations:

i) Add a new record at the end of file


ii) Retrieve and display the entire record for a given name
iii) List all names with their addresses and telephone numbers.

Note: Use fscanf and fprintf functions for reading and writing to the file.

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NAME_LENGTH 50
#define MAX_ADDRESS_LENGTH 100
#define MAX_PHONE_LENGTH 15

// Structure to represent a record

struct Record {
char name[MAX_NAME_LENGTH];
char address[MAX_ADDRESS_LENGTH]; char
phone[MAX_PHONE_LENGTH];
};

// Function prototypes
void addRecord(FILE *file);
void retrieveRecord(FILE *file, const char *name); void
listRecords(FILE *file);

int main() {
FILE *file = fopen("records.txt", "a+"); // Open file for appending and
reading

if (file == NULL) {
printf("Error opening file.\n");
return 1;
}

int choice;
char name[MAX_NAME_LENGTH];
do {
printf("\n1. Add a new record\n");
printf("2. Retrieve record by name\n");
printf("3. List all records\n"); printf("4.
Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
addRecord(file);
break;
case 2:
printf("Enter name to retrieve: ");
scanf("%s", name); retrieveRecord(file,
name);
break;
case 3:
listRecords(file);
break;
case 4:

printf("Exiting...\n"); break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);

fclose(file);
return 0;
}

void addRecord(FILE *file) {


struct Record record;

printf("Enter name: "); scanf("%s",


record.name); printf("Enter address:
"); scanf("%s", record.address);
printf("Enter phone number: ");
scanf("%s", record.phone);

fprintf(file, "%s %s %s\n", record.name, record.address, record.phone);


printf("Record added successfully.\n");
}

void retrieveRecord(FILE *file, const char *name) { struct


Record record;
int found = 0;

rewind(file); // Move file pointer to the beginning

while (fscanf(file, "%s %s %s", record.name, record.address, record.phone)


!= EOF) {
if (strcmp(record.name, name) == 0) {
printf("Name: %s\n", record.name);
printf("Address: %s\n", record.address);
printf("Phone: %s\n", record.phone); found
= 1;
break;
}
}

if (!found) {
printf("Record not found for %s.\n", name);
}
}

void listRecords(FILE *file) {


struct Record record;

rewind(file); // Move file pointer to the beginning

printf("List of records:\n");
while (fscanf(file, "%s %s %s", record.name, record.address,
record.phone) != EOF) {
printf("Name: %s, Address: %s, Phone: %s\n", record.name,
record.address, record.phone);
}
}

SAMPLE OUTPUT:
5. Modify 2 by using fread and fwrite functions for reading and writing.
Perform the following operations:

i) Insert a new record in mth position


ii) Delete a record based upon the given name
iii) Display nth record

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_EMPLOYEES 10
#define FILENAME "employee_details.bin"

// Define DOB structure struct


DateOfBirth {
int day; int
month; int
year;
};

// Define Address structure


struct Address {
char doorNo[20]; char
street[50];
char area[50];
char city[50];
int pincode;
};

// Define Employee structure


struct Employee {
int empId;
char empName[50]; struct
DateOfBirth dob; struct
Address address; char
dept[20];
float basicSalary; float
allowance[3]; float
deduction[2]; float
grossSalary; float
netSalary;
};

// Function to calculate allowances


void calculateAllowances(struct Employee *emp) {
emp->allowance[0] = 0.42 * emp->basicSalary; // Dearness Allowance
emp->allowance[1] = 0.10 * emp->basicSalary; // HRA
emp->allowance[2] = 0.15 * emp->basicSalary; // Medical Allowance
}

// Function to calculate gross salary


void calculateGrossSalary(struct Employee *emp) {
emp->grossSalary = emp->basicSalary + emp->allowance[0] + emp-
>allowance[1] + emp->allowance[2];
}

// Function to calculate deductions


void calculateDeductions(struct Employee *emp) { emp-
>deduction[0] = 0.12 * emp->basicSalary; // PF
emp->deduction[1] = 0.20 * emp->grossSalary; // Income Tax
}

// Function to calculate net salary


void calculateNetSalary(struct Employee *emp) {
emp->netSalary = emp->grossSalary - emp->deduction[0] - emp-
>deduction[1];
}
// Function to display an employee record
void displayEmployeeRecord(struct Employee emp) {
printf("Employee ID: %d\n", emp.empId);
printf("Employee Name: %s\n", emp.empName);
printf("Date of Birth: %02d-%02d-%4d\n", emp.dob.day, emp.dob.month,
emp.dob.year);
printf("Address: %s, %s, %s, %s, %d\n", emp.address.doorNo, emp.address.street,
emp.address.area, emp.address.city, emp.address.pincode);
printf("Department: %s\n", emp.dept); printf("Basic
Salary: %.2f\n", emp.basicSalary);
printf("Dearness Allowance: %.2f\n", emp.allowance[0]);
printf("HRA: %.2f\n", emp.allowance[1]); printf("Medical
Allowance: %.2f\n", emp.allowance[2]); printf("Gross Salary:
%.2f\n", emp.grossSalary); printf("PF: %.2f\n",
emp.deduction[0]);
printf("Income Tax: %.2f\n", emp.deduction[1]);
printf("Net Salary: %.2f\n", emp.netSalary); printf("\n");
}

// Function to insert a new record at position m


void insertNewRecord(int position, struct Employee newEmp) { FILE
*fp = fopen(FILENAME, "rb+");
if (fp == NULL) {
printf("Error opening file.\n"); return;
}

fseek(fp, position * sizeof(struct Employee), SEEK_SET);


fwrite(&newEmp, sizeof(struct Employee), 1, fp);

fclose(fp);
}

// Function to delete a record based on the given name


void deleteRecordByName(const char *name) {
FILE *fp = fopen(FILENAME, "rb+"); if
(fp == NULL) {
printf("Error opening file.\n"); return;
}

struct Employee emp; int


found = 0;
while (fread(&emp, sizeof(struct Employee), 1, fp) == 1) { if
(strcmp(emp.empName, name) == 0) {
found = 1;
break;
}
}

if (found) {
fseek(fp, -sizeof(struct Employee), SEEK_CUR);
struct Employee emptyEmp = {0}; // Empty employee record
fwrite(&emptyEmp, sizeof(struct Employee), 1, fp);
} else {
printf("Employee not found with name %s\n", name);
}

fclose(fp);
}

// Function to display the nth record


void displayNthRecord(int n) {
FILE *fp = fopen(FILENAME, "rb"); if
(fp == NULL) {
printf("Error opening file.\n"); return;
}

fseek(fp, (n - 1) * sizeof(struct Employee), SEEK_SET); struct


Employee emp;
fread(&emp, sizeof(struct Employee), 1, fp);
displayEmployeeRecord(emp);

fclose(fp);
}

int main() {
// Sample employee records
struct Employee employees[MAX_EMPLOYEES] = {
{101, "John Doe", {15, 5, 1990}, {"123", "Main St", "Downtown", "New
York", 10001}, "Sales", 5000.00},
{102, "Jane Smith", {20, 7, 1985}, {"456", "Elm St", "Uptown", "New
York", 10002}, "HR", 6000.00},
{103, "Michael Johnson", {10, 10, 1992}, {"789", "Oak St", "Midtown",
"New York", 10003}, "Sales", 5500.00},
{104, "Emily Davis", {5, 2, 1988}, {"101", "Pine St", "Downtown", "New
York", 10004}, "IT", 7000.00},
{105, "David Wilson", {25, 12, 1995}, {"202", "Maple St", "Suburb",
"New York", 10005}, "HR", 6200.00}
};

// Write employee records to file


FILE *fp = fopen(FILENAME, "wb"); if
(fp == NULL) {
printf("Error opening file.\n"); return
1;
}
fwrite(employees, sizeof(struct Employee), MAX_EMPLOYEES, fp); fclose(fp);

// Insert new record at position 3


struct Employee newEmp = {106, "Sarah Johnson", {8, 9, 1993}, {"111", "Cedar
St", "Downtown", "New York", 10006}, "Sales", 5800.00};
insertNewRecord(3, newEmp);

// Delete record with name "Emily Davis" deleteRecordByName("Emily


Davis");

// Display 2nd record


printf("2nd Record:\n");
displayNthRecord(2);

return 0;
}

SAMPLE OUTPUT:
Learning Outcome:

I am able to implement user defined datatypes in C with the following


features:

● Using structures
● Passing structures to a function
● Using pointers
● Using Files
I am able to adapt to the following best practices
● Modular programming and incremental programming
● Using user defined data types
● Multi-file program with user defined header file

You might also like