CP Master Manual-62-88

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

UNIT IV

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()

i) Write a C program to find the sum of a 1D array using malloc()

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;

// Input the size of the array


printf("Enter the number of elements: ");
scanf("%d", &n);

// Allocate memory dynamically


arr = (int *)malloc(n * sizeof(int));

// Check if memory allocation is successful


if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit the program with an error
}

// Input the elements of the array


printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Calculate the sum of elements


for (int i = 0; i < n; i++) {
sum += arr[i];
}

DNRCET Page 63
// Output the sum
printf("Sum of the elements: %d\n", sum);

// Free dynamically allocated memory


free(arr);
return 0;
}
Output:
Enter the number of elements: 5
Enter 5 integers:
25
65
74
66
10
Sum of the elements: 240

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

// Input number of students


Print "Enter the number of students: "
Read n

// Input student details


for i = 0 to n-1 do
Print "Enter details for student ", i+1
Print "Name: "
Read students[i].name

// Initialize total marks


students[i].total = 0

// Input marks for each subject


for j = 0 to number_of_subjects - 1 do
Print "Enter marks for subject ", j+1, ": "
Read students[i].marks[j]
students[i].total = students[i].total + students[i].marks[j]

// Calculate average marks


students[i].average = students[i].total / number_of_subjects

// Calculate total and average marks for all students


total_marks = 0
for i = 0 to n-1 do
total_marks = total_marks + students[i].total

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

// Define a structure for student


struct Student {
char name[50];
int marks[5]; // Assuming 5 subjects for simplicity
int total;
float average;
};

int main() {
int n;
struct Student *students;
int total_marks = 0;
float average_marks = 0.0;

// Input the number of students


printf("Enter the number of students: ");
scanf("%d", &n);

// Allocate memory dynamically for array of students


students = (struct Student *)malloc(n * sizeof(struct Student));

// Input details for each student


for (int i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]s", students[i].name);

// Input marks for each subject


students[i].total = 0;
printf("Enter marks for 5 subjects: ");
for (int j = 0; j < 5; j++) {
scanf("%d", &students[i].marks[j]);
students[i].total += students[i].marks[j];
}

// Calculate average marks


students[i].average = (float)students[i].total / 5.0;
}

// Calculate total and average marks for all students


total_marks = 0;
for (int i = 0; i < n; i++) {
total_marks += students[i].total;
}

DNRCET Page 66
average_marks = (float)total_marks / n;

// Output total and average marks


printf("\nTotal marks of all students: %d\n", total_marks);
printf("Average marks of all students: %.2f\n", average_marks);

// Free dynamically allocated memory


free(students);

return 0;
}
Output:
Enter the number of students: 2

Enter details for student 1:


Name: AAA
Enter marks for 5 subjects: 98
45
67
87
78

Enter details for student 2:


Name: BBB
Enter marks for 5 subjects: 67
98
67
66
88

Total marks of all students: 761


Average marks of all students: 380.50

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 number of students


Print "Enter the number of students: "
Read n

// Allocate memory dynamically for array of students


students = calloc(n, size of Student)

// Check if memory allocation is successful


if students == NULL then
Print "Memory allocation failed."
Exit program with error

// Input student details


for i = 0 to n-1 do
Print "Enter details for student ", i+1
Print "Name: "
Read students[i].name

// 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"

// Display failed students list


Print "Failed Students List:"
for i = 0 to n-1 do
if students[i].result == "Fail" then
Print students[i].name, " Marks: ", students[i].marks

// Free dynamically allocated memory


free(students)

// End
}
Program:
#include <stdio.h>
#include <stdlib.h> // for calloc and free
#include<string.h>

// Define a structure for student


struct Student {
char name[50];
int marks;
char result[10];
};

int main() {
int n;
struct Student *students;

// Input the number of students


printf("Enter the number of students: ");
scanf("%d", &n);

// Allocate memory dynamically for array of students


students = (struct Student *)calloc(n, sizeof(struct Student));

// Check if memory allocation is successful


if (students == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit the program with an error
}

// Input details for each student


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

DNRCET Page 69
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]s", students[i].name);

printf("Enter marks: ");


scanf("%d", &students[i].marks);

// Determine result based on marks (e.g., pass/fail)


if (students[i].marks >= 50) {
strcpy(students[i].result, "Pass");
} else {
strcpy(students[i].result, "Fail");
}
}

// Display failed students list


printf("\nFailed Students List:\n");
for (int i = 0; i < n; i++) {
if (strcmp(students[i].result, "Fail") == 0) {
printf("%s\tMarks: %d\n", students[i].name, students[i].marks);
}
}

// Free dynamically allocated memory


free(students);

return 0;
}
Output:
Enter the number of students: 3

Enter details for student 1:


Name: AAA
Enter marks: 45

Enter details for student 2:


Name: BBB
Enter marks: 31

Enter details for student 3:


Name: CCC
Enter marks: 67

Failed Students List:


AAA Marks: 45
BBB Marks: 31

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

// Read number of students from command line argument


n = atoi(argv[1]) // Assuming argv[1] contains the number of students

// Read student details from command line arguments


for i = 0 to n-1 do
students[i].name = argv[2 + i*6] // Assuming argv[2 + i*6] is student name
for j = 0 to number_of_subjects-1 do
students[i].marks[j] = atoi(argv[3 + i*6 + j]) // Assuming argv[3 + i*6 + j] is marks
for subject j
// Calculate total marks
students[i].total_marks = 0
for j = 0 to number_of_subjects-1 do

DNRCET Page 71
students[i].total_marks = students[i].total_marks + students[i].marks[j]

// Display student details


for i = 0 to n-1 do
Print "Student Name: ", students[i].name
for j = 0 to number_of_subjects-1 do
Print "Subject ", j+1, " Marks: ", students[i].marks[j]
Print "Total Marks: ", students[i].total_marks
Print "\n"

// End
}
Program:

#include <stdio.h>
#include <stdlib.h> // for atoi function

#define MAX_SUBJECTS 5 // Assuming a maximum of 5 subjects per student

struct Student {
char name[50];
int marks[MAX_SUBJECTS];
int total_marks;
};

int main(int argc, char *argv[]) {


// Check if correct number of arguments are provided
if (argc < 2 || (argc - 2) % (MAX_SUBJECTS + 1) != 0) {
printf("Usage: %s <number of students> <student1 name> <marks1> <marks2> ...
<student2 name> <marks1> <marks2> ...\n", argv[0]);
return 1;
}

// Read number of students from command line argument


int n = atoi(argv[1]);
if (n <= 0 || (argc - 2) != n * (MAX_SUBJECTS + 1)) {
printf("Invalid number of students provided.\n");
return 1;
}

// Initialize an array of Student structures


struct Student students[n];

// Initialize index to traverse command line arguments


int arg_index = 2;

// Read student details from command line arguments


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

DNRCET Page 72
// Copy student name
snprintf(students[i].name, sizeof(students[i].name), "%s", argv[arg_index]);
arg_index++;

// Initialize total marks for current student


students[i].total_marks = 0;

// Read marks for each subject


for (int j = 0; j < MAX_SUBJECTS; j++) {
students[i].marks[j] = atoi(argv[arg_index]);
students[i].total_marks += students[i].marks[j];
arg_index++;
}
}

// Display student details


printf("Student Details:\n");
for (int i = 0; i < n; i++) {
printf("Name: %s\n", students[i].name);
printf("Marks: ");
for (int j = 0; j < MAX_SUBJECTS; j++) {
printf("%d ", students[i].marks[j]);
}
printf("\nTotal Marks: %d\n", students[i].total_marks);
printf("\n");
}

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)

memcpy(new_ptr, ptr, copy_size)

free(ptr)

return new_ptr

DNRCET Page 74
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // for memcpy

// Function to implement realloc()


void *my_realloc(void *ptr, size_t new_size) {
// If ptr is NULL, allocate new memory block of size new_size
if (ptr == NULL) {
return malloc(new_size);
}

// If new_size is 0, free memory block pointed by ptr and return NULL


if (new_size == 0) {
free(ptr);
return NULL;
}

// Allocate new memory block of size new_size


void *new_ptr = malloc(new_size);
if (new_ptr == NULL) {
return NULL; // Allocation failed
}

// Get current size of allocated memory block


size_t current_size = malloc_usable_size(ptr);

// Copy data from old block to new block


size_t copy_size = current_size < new_size ? current_size : new_size;
memcpy(new_ptr, ptr, copy_size);

// Free old memory block


free(ptr);

// Return pointer to the new memory block


return new_ptr;
}

int main() {
// Example usage of my_realloc()
int *arr = malloc(5 * sizeof(int));
if (arr == NULL) {
perror("malloc failed");
return 1;
}

// Initialize array elements


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

DNRCET Page 75
arr[i] = i + 1;
}

// Reallocate array to 10 elements


int *new_arr = my_realloc(arr, 10 * sizeof(int));
if (new_arr == NULL) {
perror("realloc failed");
return 1;
}

// Print array elements after reallocation


printf("Array elements after reallocation:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", new_arr[i]);
}
printf("\n");

free(new_arr); // Free dynamically allocated memory

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.

i) Create and display a singly linked list using self-referential structure.

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:

// Define a structure for a node in the singly linked list

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

// Function to insert a new node at the beginning of the linked list


function insertAtBeginning(headRef, data):
newNode = createNode(data)
if headRef == null:
headRef = newNode
else:
newNode.next = headRef
headRef = newNode

// Function to display the contents of the linked list


function displayList(head):
current = head
while current != null:
print(current.data)
current = current.next

// Main program
function main():
head = null

// Insert nodes at the beginning


insertAtBeginning(head, 5)
insertAtBeginning(head, 10)
insertAtBeginning(head, 15)

// Display the linked list


displayList(head)

Program:

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

// Define the structure of a node


struct Node {
int data;
struct Node *next;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node *newNode = (struct Node*) malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
return NULL;
}
newNode->data = data;

DNRCET Page 78
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the beginning of the linked list


void insertAtBeginning(struct Node **headRef, int data) {
struct Node *newNode = createNode(data);
if (newNode == NULL) {
return; // Failed to create node
}
newNode->next = *headRef;
*headRef = newNode;
}

// Function to display the linked list


void displayList(struct Node *head) {
struct Node *current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main() {
struct Node *head = NULL;

// Insert nodes at the beginning


insertAtBeginning(&head, 5);
insertAtBeginning(&head, 10);
insertAtBeginning(&head, 15);

// Display the linked list


printf("Linked List: ");
displayList(head);

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;
};

// Define a union for storing different types of data


union Data {
int i;
float f;
string str;
};

// Main function
function main():
// Declare variables
struct Person person1;
union Data data;

// Initialize structure members


person1.name = "John Doe";
person1.age = 30;
person1.height = 6.0;

// Display structure data


print("Structure (Person):");
print("Name: " + person1.name);
print("Age: " + person1.age);
print("Height: " + person1.height);

// Initialize and use union members


data.i = 10;
print("\nUnion (Data):");
print("data.i : " + data.i);

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);

// End of main function

Program:
#include <stdio.h>
#include <string.h>

// Define a structure for a person


struct Person {
char name[50];
int age;
float height;
};

// Define a union for storing different types of data


union Data {
int i;
float f;
char str[20];
};

int main() {
struct Person person1;
union Data data;

// Demonstrating structure usage


printf("Size of struct Person: %lu bytes\n", sizeof(person1));

strcpy(person1.name, "John Doe");


person1.age = 30;
person1.height = 6.0;

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");

// Demonstrating union usage


printf("Size of union Data: %lu bytes\n", sizeof(data));

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);

// Accessing union members after assigning a string


printf("After assigning a string to data.str:\n");
printf("data.i : %d\n", data.i); // Output might not be meaningful since data.i was
overwritten
printf("data.f : %.2f\n", data.f); // Output might not be meaningful since data.f was
overwritten
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

Size of union Data: 20 bytes


data.i : 10
data.f : 3.14
data.str : Hello
After assigning a string to data.str:
data.i : 1819043144
data.f : 1143139122437582505939828736.00
data.str : Hello

iii) Write a C program to shift/rotate using bitfields.


Algorithm:

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:

// Define a structure with bitfields


struct BitFields {
unsigned int field1 : 4; // 4 bits

DNRCET Page 82
unsigned int field2 : 8; // 8 bits
};

// Function to perform left shift on bitfields


function leftShift(struct BitFields *bf):
bf->field1 <<= 1; // Left shift by 1 bit
bf->field2 <<= 1; // Left shift by 1 bit

// Function to perform right shift on bitfields


function rightShift(struct BitFields *bf):
bf->field1 >>= 1; // Right shift by 1 bit
bf->field2 >>= 1; // Right shift by 1 bit

// Function to perform rotate left on bitfields


function rotateLeft(struct BitFields *bf):
unsigned int carry1 = bf->field1 >> 3; // Capture the carry from field1
unsigned int carry2 = bf->field2 >> 7; // Capture the carry from field2
bf->field1 = (bf->field1 << 1) | carry2; // Rotate left field1 and include carry from field2
bf->field2 = (bf->field2 << 1) | carry1; // Rotate left field2 and include carry from field1

// Function to perform rotate right on bitfields


function rotateRight(struct BitFields *bf):
unsigned int carry1 = bf->field1 & 0x1; // Capture the carry from field1
unsigned int carry2 = bf->field2 & 0x1; // Capture the carry from field2
bf->field1 = (bf->field1 >> 1) | (carry2 << 3); // Rotate right field1 and include carry from
field2
bf->field2 = (bf->field2 >> 1) | (carry1 << 7); // Rotate right field2 and include carry from
field1

// Main function
function main():
// Declare a variable of type struct BitFields
struct BitFields bf;

// Initialize the bitfields with example values


bf.field1 = 0b1010; // 4 bits
bf.field2 = 0b11001100; // 8 bits

// Display initial values


print("Initial Bitfields:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// Perform left shift


leftShift(&bf);
print("\nAfter Left Shift:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// Perform right shift


rightShift(&bf);
print("\nAfter Right Shift:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

DNRCET Page 83
// Perform rotate left
rotateLeft(&bf);
print("\nAfter Rotate Left:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// Perform rotate right


rotateRight(&bf);
print("\nAfter Rotate Right:");
print("field1: " + bf.field1);
print("field2: " + bf.field2);

// End of main function

Program:

#include <stdio.h>

// Define a structure with bitfields


struct BitFields {
unsigned int field1 : 4; // 4 bits
unsigned int field2 : 8; // 8 bits
};

// Function to perform left shift on bitfields


void leftShift(struct BitFields *bf) {
bf->field1 <<= 1; // Left shift by 1 bit
bf->field2 <<= 1; // Left shift by 1 bit
}

// Function to perform right shift on bitfields


void rightShift(struct BitFields *bf) {
bf->field1 >>= 1; // Right shift by 1 bit
bf->field2 >>= 1; // Right shift by 1 bit
}

// Function to perform rotate left on bitfields


void rotateLeft(struct BitFields *bf) {
unsigned int carry1 = bf->field1 >> 3; // Capture the carry from field1
unsigned int carry2 = bf->field2 >> 7; // Capture the carry from field2
bf->field1 = (bf->field1 << 1) | carry2; // Rotate left field1 and include carry from field2
bf->field2 = (bf->field2 << 1) | carry1; // Rotate left field2 and include carry from field1
}

// Function to perform rotate right on bitfields


void rotateRight(struct BitFields *bf) {
unsigned int carry1 = bf->field1 & 0x1; // Capture the carry from field1
unsigned int carry2 = bf->field2 & 0x1; // Capture the carry from field2
bf->field1 = (bf->field1 >> 1) | (carry2 << 3); // Rotate right field1 and include carry from
field2
bf->field2 = (bf->field2 >> 1) | (carry1 << 7); // Rotate right field2 and include carry from
field1
}

int main() {

DNRCET Page 84
// Declare a variable of type struct BitFields
struct BitFields bf;

// Initialize the bitfields with example values


bf.field1 = 0b1010; // 4 bits
bf.field2 = 0b11001100; // 8 bits

// Display initial values


printf("Initial Bitfields:\n");
printf("field1: %u (binary: %04b)\n", bf.field1, bf.field1);
printf("field2: %u (binary: %08b)\n", bf.field2, bf.field2);

// Perform left shift


leftShift(&bf);
printf("\nAfter Left Shift:\n");
printf("field1: %u (binary: %04b)\n", bf.field1, bf.field1);
printf("field2: %u (binary: %08b)\n", bf.field2, bf.field2);

// Perform right shift


rightShift(&bf);
printf("\nAfter Right Shift:\n");
printf("field1: %u (binary: %04b)\n", bf.field1, bf.field1);
printf("field2: %u (binary: %08b)\n", bf.field2, bf.field2);

// Perform rotate left


rotateLeft(&bf);
printf("\nAfter Rotate Left:\n");
printf("field1: %u (binary: %04b)\n", bf.field1, bf.field1);
printf("field2: %u (binary: %08b)\n", bf.field2, bf.field2);

// Perform rotate right


rotateRight(&bf);
printf("\nAfter Rotate Right:\n");
printf("field1: %u (binary: %04b)\n", bf.field1, bf.field1);
printf("field2: %u (binary: %08b)\n", bf.field2, bf.field2);

return 0;
}
Output:
Initial Bitfields:
field1: 10 (binary: %04b)
field2: 204 (binary: %08b)

After Left Shift:


field1: 4 (binary: %04b)
field2: 152 (binary: %08b)

After Right Shift:


field1: 2 (binary: %04b)
field2: 76 (binary: %08b)

After Rotate Left:


field1: 4 (binary: %04b)
field2: 152 (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:

// Define a structure with multiple members


struct Person {
string name;
int age;
float height;
};

// Function to copy one structure variable to another of the same type


function copyStruct(struct Person source, struct Person *destination):
// Copy each member from source to destination
destination.name = source.name;
destination.age = source.age;
destination.height = source.height;

// Main function
function main():
// Declare two variables of type struct Person
struct Person person1, person2;

// Initialize person1 with example values


person1.name = "Alice";
person1.age = 25;
person1.height = 5.6;

// Display initial values of person1


print("Initial values of person1:");
print("Name: " + person1.name);
print("Age: " + person1.age);
print("Height: " + person1.height);

// Copy person1 to person2


copyStruct(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);

// End of main function

Program:

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

// Define a structure with multiple members


struct Person {
char name[50];
int age;
float height;
};

// Function to copy one structure variable to another of the same type


void copyStruct(struct Person source, struct Person *destination) {
// Using strcpy to copy strings since direct assignment won't work for arrays
strcpy(destination->name, source.name);
destination->age = source.age;
destination->height = source.height;
}

int main() {
// Declare two variables of type struct Person
struct Person person1, person2;

// Initialize person1 with example values


strcpy(person1.name, "Alice");
person1.age = 25;
person1.height = 5.6;

// Display initial values of person1


printf("Initial values of person1:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.1f\n", person1.height);

// Copy person1 to person2


copyStruct(person1, &person2);

// Display values of person2 after copy


printf("\nValues of person2 after copy:\n");
printf("Name: %s\n", person2.name);
printf("Age: %d\n", person2.age);
printf("Height: %.1f\n", person2.height);

return 0;
}

DNRCET Page 87
Output:
Initial values of person1:
Name: Alice
Age: 25
Height: 5.6

Values of person2 after copy:


Name: Alice
Age: 25
Height: 5.6

DNRCET Page 88

You might also like