CP Master Manual-62-88
CP Master Manual-62-88
CP Master Manual-62-88
WEEK 9:
Objective: Explore pointers to manage a dynamic array of integers, including memory
allocation & value initialization, resizing changing and reordering the contents of an array
and memory de-allocation using malloc (), calloc (), realloc () and free () functions. Gain
experience processing command-line arguments received by C
Suggested Experiments/Activities:
Tutorial 9: Pointers, structures and dynamic memory allocation
Lab 9: Pointers and structures, memory dereferences.
i) Write a C program to find the sum of a 1D array using malloc()
ii) Write a C program to find the total, average of n students using structures
iii) Enter n students data using calloc() and display failed students list
iv) Read student name and marks from the command line and display the student details
along with the total.
v) Write a C program to implement realloc()
Algorithm:
Step-1: Start
Step-2: Input the Size of the Array:
Prompt the user to enter the number of elements ( n) in the array.
Step-3: Allocate Memory Dynamically:
Use malloc() to allocate memory dynamically for an integer array of size n.
Step-4: Check for Successful Allocation:
Verify if memory allocation was successful ( arr != NULL). If not, handle the error
appropriately (e.g., display an error message and exit).
Step-5: Input Array Elements:
Read or generate n integers and store them in the allocated memory space ( arr).
Step-6: Calculate the Sum:
Initialize a variable (sum) to zero.
Traverse through the array and add each element to sum.
Step-7: Output the Sum:
Display the computed sum of the array elements.
Step-8: Free Dynamically Allocated Memory:
Use free(arr) to release the memory allocated for the array.
Step-9: Stop
Pseudo code:
// Pseudo-code for finding sum of 1D array using malloc()
// Declare variables
int n
int* arr
int sum = 0
// Input size of array
Print "Enter the number of elements: "
Read n
// Allocate memory dynamically
arr = malloc(n * sizeof(int))
DNRCET Page 62
if arr == NULL then
Print "Memory allocation failed."
Exit program
// Input array elements
Print "Enter n integers:"
for i = 0 to n-1 do
Read arr[i]
// Calculate sum of elements
sum = 0
for i = 0 to n-1 do
sum = sum + arr[i]
// Output sum of elements
Print "Sum of elements:", sum
// Free dynamically allocated memory
free(arr)
Program:
#include <stdio.h>
#include <stdlib.h> // for malloc and free
int main() {
int n;
int *arr;
int sum = 0;
DNRCET Page 63
// Output the sum
printf("Sum of the elements: %d\n", sum);
ii) Write a C program to find the total, average of n students using structures
Algorithm:
Step-1: Start
Step-2: Define a Structure for Student:
Create a structure student that contains fields for name, marks, total, and
average.
Step-3: Input the Number of Students (n):
Prompt the user to enter the number of students ( n).
Step-4: Declare an Array of Structures:
Declare an array students of type student with size n.
Step-5: Input Student Details:
Use a loop to input details for each student:
o Read the name of the student.
o Read marks for each subject (assuming fixed number of
subjects or dynamically allocate based on input).
o Calculate total marks for each student.
o Calculate average marks for each student.
Step-6: Calculate Total and Average for All Students:
Initialize variables total_marks and average_marks.
Traverse through the students array:
o Accumulate total_marks by adding each student's total.
Calculate average_marks as total_marks / n.
Step-7: Output Results:
Display the total_marks and average_marks.
Step-8: Stop
Pseudo code:
// Pseudo-code to find total and average of n students using structures
// Define Structure
struct Student {
string name
DNRCET Page 64
int marks[number_of_subjects]
int total
float average
}
// Start
main() {
// Declare variables
int n
struct Student students[n]
int total_marks = 0
float average_marks = 0.0
average_marks = total_marks / n
// Output results
Print "Total marks of all students: ", total_marks
Print "Average marks of all students: ", average_marks
// End
}
DNRCET Page 65
Program:
#include <stdio.h>
#include <stdlib.h> // for malloc
int main() {
int n;
struct Student *students;
int total_marks = 0;
float average_marks = 0.0;
DNRCET Page 66
average_marks = (float)total_marks / n;
return 0;
}
Output:
Enter the number of students: 2
iii)Enter n students data using calloc() and display failed students list
Algorithm:
Step-1: Start
Step-2: Define a Structure for Student:
Create a structure Student with fields for name, marks, and result.
Step-3: Input the Number of Students (n):
Prompt the user to enter the number of students ( n).
Step-4: Allocate Memory Dynamically Using calloc():
Use calloc() to allocate memory dynamically for an array of n Student
structures.
Check if calloc() was successful (i.e., array pointer is not NULL).
Step-5: Input Student Details:
For each student from 0 to n-1:
o Prompt and read the name of the student.
o Input the marks (e.g., for one or more subjects).
DNRCET Page 67
o Determine the result based on a pass/fail criterion (e.g., total
marks >= pass marks).
Step-6: Display Failed Students:
Traverse through the array of students:
If a student's result indicates failure, display their name and marks.
Step-7: Free Dynamically Allocated Memory:
Use free() to release the memory allocated by calloc().
Step-8: Stop
Pseudo code:
// Pseudo-code to enter data for n students using calloc() and display failed students list
// Define Structure
struct Student {
string name
int marks
string result
}
// Start
main() {
// Declare variables
int n
struct Student students[n]
// Input marks
Print "Enter marks: "
Read students[i].marks
DNRCET Page 68
// Determine result based on marks (e.g., pass/fail)
if students[i].marks >= 50 then
students[i].result = "Pass"
else
students[i].result = "Fail"
// End
}
Program:
#include <stdio.h>
#include <stdlib.h> // for calloc and free
#include<string.h>
int main() {
int n;
struct Student *students;
DNRCET Page 69
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]s", students[i].name);
return 0;
}
Output:
Enter the number of students: 3
DNRCET Page 70
iv) Read student name and marks from the command line and display the student details
along with the total.
Algorithm:
Step-1: Start
Step-2: Input Number of Students (n):
Read n from command line arguments (assuming n is provided as an
argument).
Step-3: Declare Variables:
Declare an array students of size n to store student details.
Declare variables total_marks and average_marks for calculation.
Step-4: Read Student Details:
For each student from 0 to n-1:
o Read student name from command line argument.
o Read marks for each subject from command line argument.
o Compute total marks for the student.
Step-5: Calculate Total Marks:
For each student, calculate the sum of their marks to get total_marks.
Step-6: Display Student Details:
For each student:
Print student name, marks for each subject, and total marks.
Step-7: End
Pseudo code:
// Pseudo-code to read student name and marks from command line and display details
// Start
main(int argc, char *argv[]) {
// Declare variables
int n
struct Student {
string name
int marks[number_of_subjects]
int total_marks
}
struct Student students[n]
int total_marks
DNRCET Page 71
students[i].total_marks = students[i].total_marks + students[i].marks[j]
// End
}
Program:
#include <stdio.h>
#include <stdlib.h> // for atoi function
struct Student {
char name[50];
int marks[MAX_SUBJECTS];
int total_marks;
};
DNRCET Page 72
// Copy student name
snprintf(students[i].name, sizeof(students[i].name), "%s", argv[arg_index]);
arg_index++;
return 0;
}
DNRCET Page 73
v) Write a C program to implement realloc()
Algorithm:
Step-1: Start
Step-2: Function Definition:
Define a function my_realloc(void *ptr, size_t new_size).
Step-3: Parameters:
ptr: Pointer to the previously allocated memory block (can be NULL).
new_size: New size in bytes that the memory block should be resized to.
Step-4: Edge Cases:
If ptr is NULL:
Allocate a new block of memory of size new_size using malloc() and return the
pointer.
If new_size is 0:
Free the memory block pointed by ptr using free(ptr) and return
NULL.
Step-5: Allocate New Block:
Allocate a new block of memory of size new_size using malloc(new_size).
Step-6: Copy Data (if necessary):
If ptr is not NULL and new_size is greater than 0:
o Calculate the minimum size to copy (current_size), which is the
lesser of the current allocated size (malloc_usable_size(ptr)) or
new_size.
o Allocate a new memory block (new_ptr) of new_size bytes.
o Copy the contents of the old memory block ( ptr) to the new memory
block (new_ptr) using memcpy(new_ptr, ptr, current_size).
o Free the old memory block using free(ptr).
Step-7: Return New Pointer:
Return the pointer to the new memory block (new_ptr).
Step-8: Stop
Pseudo code:
function my_realloc(ptr, new_size):
if ptr is NULL:
return malloc(new_size)
if new_size is 0:
free(ptr)
return NULL
new_ptr = malloc(new_size)
if new_ptr is NULL:
return NULL // Allocation failed
current_size = size_of_allocated_block(ptr)
copy_size = min(current_size, new_size)
free(ptr)
return new_ptr
DNRCET Page 74
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // for memcpy
int main() {
// Example usage of my_realloc()
int *arr = malloc(5 * sizeof(int));
if (arr == NULL) {
perror("malloc failed");
return 1;
}
DNRCET Page 75
arr[i] = i + 1;
}
return 0;
}
Output:
Array elements after reallocation:
1234500000
DNRCET Page 76
WEEK 10:
Objective: Experiment with C Structures, Unions, bit fields and self-referential structures
(Singly linked lists) and nested structures
Suggested Experiments/Activities:
Tutorial 10: Bitfields, Self-Referential Structures, Linked lists
Lab10 :
Bitfields, linked lists Read and print a date using dd/mm/yyyy format using bit-fields and
differentiate the same without using bit- fields
i) Create and display a singly linked list using self-referential structure.
ii) Demonstrate the differences between structures and unions using a C program.
iii) Write a C program to shift/rotate using bitfields.
iv) Write a C program to copy one structure variable to another structure of the
same type.
Algorithm:
Step-1: Start
Step-2: Define the Node Structure:
Create a structure Node with two components
o data: to store the data of the node (could be an integer, string, etc. depending
on the application).
o next: a pointer to the next node in the list.
Step-3: Initialize Functions:
Define functions for basic operations such as creating a new node, inserting nodes
at the beginning/end, and displaying the list.
Step-4: Function to Create a New Node:
Create a function createNode(int data) to dynamically allocate memory for a new
node and initialize its data and next pointer.
Step-5: Function to Insert Node at the Beginning:
Create a function insertAtBeginning(struct Node **headRef, int data) to insert a
new node at the beginning of the linked list.
Step-6: Function to Display the Linked List:
Create a function displayList(struct Node *head) to traverse and display all nodes
in the linked list.
Step-7: Main Function:
Implement the main function to test the linked list operations.
Step-8: Stop
Pseudo code:
struct Node {
int data;
Node next; // Self-referential structure: Node contains a pointer to another Node
}
DNRCET Page 77
// Function to create a new node with given data
function createNode(data):
newNode = new Node
newNode.data = data
newNode.next = null
return newNode
// Main program
function main():
head = null
Program:
#include <stdio.h>
#include <stdlib.h>
DNRCET Page 78
newNode->next = NULL;
return newNode;
}
int main() {
struct Node *head = NULL;
return 0;
}
Output:
Linked List: 15 -> 10 -> 5 -> NULL
ii) Demonstrate the differences between structures and unions using a C program.
Algorithm:
Step-1: Start
Step-2: Define a Structure:
Create a structure (struct) that contains multiple members of different data
types.
Step-3: Define a Union:
Create a union (union) that contains members of different data types, possibly
overlapping in memory.
Step-4: Allocate Memory:
DNRCET Page 79
Show how memory is allocated for structures and unions.
Display the size of each structure and union using sizeof().
Step-5: Access Members:
Access and modify members of structures and unions.
Observe how modifications in one member of a union affect other members.
Step-6: Demonstrate Usage:
Use structures when you need to store and access multiple pieces of related
data.
Use unions when you need to store different types of data in the same memory
location.
Step-7: Stop.
Pseudo code:
// Define a structure for a person
struct Person {
string name;
int age;
float height;
};
// Main function
function main():
// Declare variables
struct Person person1;
union Data data;
data.f = 3.14;
print("data.f : " + data.f);
data.str = "Hello";
print("data.str : " + data.str);
DNRCET Page 80
// Accessing union members after assigning a string
print("\nAfter assigning a string to data.str:");
print("data.i : " + data.i); // Output might not be meaningful since data.i was overwritten
print("data.f : " + data.f); // Output might not be meaningful since data.f was overwritten
print("data.str : " + data.str);
Program:
#include <stdio.h>
#include <string.h>
int main() {
struct Person person1;
union Data data;
printf("Person Details:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f feet\n", person1.height);
printf("\n");
data.i = 10;
printf("data.i : %d\n", data.i);
data.f = 3.14;
printf("data.f : %.2f\n", data.f);
strcpy(data.str, "Hello");
DNRCET Page 81
printf("data.str : %s\n", data.str);
return 0;
}
Output:
Size of struct Person: 60 bytes
Person Details:
Name: John Doe
Age: 30
Height: 6.00 feet
Step-1: Start
Step-2: Define a Structure with Bitfields:
Create a structure (struct) with bitfields to hold the data that needs to be
shifted or rotated.
Step-3: Initialize the Structure:
Initialize the structure with data values.
Step-4: Perform Shift Operation:
Use bitwise shift operators (<<, >>) to perform left or right shifts on the
bitfields.
Step-5: Perform Rotate Operation:
For rotate operations, implement custom rotate functions using bitwise
operations (<<, >>, |, &) to handle wrapping around bits properly.
Step-6: Display Results:
Output the results after each shift or rotate operation to observe the changes in
the bitfields.
Step-7: Stop.
Pseudo code:
DNRCET Page 82
unsigned int field2 : 8; // 8 bits
};
// Main function
function main():
// Declare a variable of type struct BitFields
struct BitFields bf;
DNRCET Page 83
// Perform rotate left
rotateLeft(&bf);
print("\nAfter Rotate Left:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);
Program:
#include <stdio.h>
int main() {
DNRCET Page 84
// Declare a variable of type struct BitFields
struct BitFields bf;
return 0;
}
Output:
Initial Bitfields:
field1: 10 (binary: %04b)
field2: 204 (binary: %08b)
DNRCET Page 85
After Rotate Right:
field1: 2 (binary: %04b)
iv) Write a C program to copy one structure variable to another structure of the same type.
Algorithm:
Step-1: Start
Step-2: Define the Structure:
Create a structure (struct) with multiple members of various data types.
Step-3: Declare Variables:
Declare two variables of the structure type ( struct) to store data.
Step-4: Initialize Source Structure:
Assign values to the members of the source structure.
Step-5: Copy Structure:
Copy each member from the source structure to the destination structure.
Step-6: Display Results (optional):
Output the values of the destination structure to verify the copy operation.
Step-7: Stop
Pseudo code:
// Main function
function main():
// Declare two variables of type struct Person
struct Person person1, person2;
DNRCET Page 86
// Display values of person2 after copy
print("\nValues of person2 after copy:");
print("Name: " + person2.name);
print("Age: " + person2.age);
print("Height: " + person2.height);
Program:
#include <stdio.h>
#include <string.h>
int main() {
// Declare two variables of type struct Person
struct Person person1, person2;
return 0;
}
DNRCET Page 87
Output:
Initial values of person1:
Name: Alice
Age: 25
Height: 5.6
DNRCET Page 88