Data Structures Lab [BCSL305] Department of CSE- Data Science
Program 1: Develop a Program in C for the following: Declare a calendar as an array of 7 elements (A dynamically Created array) to represent 7 days of a week. Each Element of the array is a structure having three fields. The first field is the name of the Day (A dynamically allocated String), The second field is the date of the Day (A integer), the third field is the description of the activity for a particular day (A dynamically allocated String). Write functions create(), read() and display(); to create the calendar, to read the data from the keyboard and to print weeks activity details report on screen. Department of CSE- Data Science
Procedure Define a structure to represent a day in the calendar Function to create a calendar – createCalendar () Function to read data from the keyboard- readCalendarData () Function to display the calendar- displayCalendar () Department of CSE- Data Science
// structure to represent a day in the calendar struct Day { char* dayName ; int date; char* activity; }; Department of CSE- Data Science Stores name of the day Stores date Description of the planned activity
// Function to create the calendar struct Day* createCalendar () { struct Day* calendar = (struct Day*)malloc(7 * sizeof (struct Day)); for (int i = 0; i < 7; i ++) { calendar[ i ]. dayName = (char*)malloc(20 * sizeof (char)); calendar[ i ].activity = (char*)malloc(100 * sizeof (char)); } return calendar; } Department of CSE- Data Science Allocates memory for 7 days & returns a pointer to the block of the memory For each day, allocate memory for day name & activity
// Function to read data from the keyboard void readCalendarData (struct Day* calendar) { for (int i = 0; i < 7; i ++) { printf ("Enter the day name for Day %d: ", i + 1); scanf ("%s", calendar[ i ]. dayName ); printf ("Enter the date for Day %d: ", i + 1); scanf ("%d", &calendar[ i ].date); printf ("Enter the activity for Day %d: ", i + 1); scanf (" %[^\n]s", calendar[ i ].activity); } } Department of CSE- Data Science Runs the loop for 7 times asking the user to enter Day name Date Activity
// function to display the calendar void displayCalendar (struct Day* calendar) { printf ("Weekly Activity Report:\n\n"); for (int i = 0; i < 7; i ++) { printf ("Day %d: %s\n", i + 1, calendar[ i ]. dayName ); printf ("Date: %d\n", calendar[ i ].date); printf ("Activity: %s\n", calendar[ i ].activity); printf ("\n"); } } Department of CSE- Data Science Prints each day’s details name, date , activity
//main() function int main() { struct Day* calendar = createCalendar (); readCalendarData (calendar); displayCalendar (calendar); // Free memory for (int i = 0; i < 7; i ++) { free(calendar[ i ]. dayName ); free(calendar[ i ].activity); } free(calendar); return 0; } Department of CSE- Data Science