0% found this document useful (0 votes)
3 views9 pages

C Programming Assignment Answer 2

The document provides several C programming assignments, including programs for deleting an element from an array, printing the transpose of a matrix, and sorting employee records using structures. It also explains dynamic memory allocation techniques such as malloc, calloc, realloc, and free, along with their usage. Additionally, it outlines the differences between structures and unions in C.

Uploaded by

parekhurvi340
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

C Programming Assignment Answer 2

The document provides several C programming assignments, including programs for deleting an element from an array, printing the transpose of a matrix, and sorting employee records using structures. It also explains dynamic memory allocation techniques such as malloc, calloc, realloc, and free, along with their usage. Additionally, it outlines the differences between structures and unions in C.

Uploaded by

parekhurvi340
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

C Programming Assignment Answer

Write a program to delete an element from a given


location in an array.
#include <stdio.h>
int main() {
int arr[100], n, pos, i;
// Input the size of the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Input array elements
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Input position to delete
printf("Enter the position to delete (0-based index): ");
scanf("%d", &pos);
// Check for valid position
if (pos < 0 || pos >= n) {
printf("Invalid position!\n");
} else {
// Shift elements to the left
for (i = pos; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
n--; // Reduce size of array
// Print updated array
printf("Array after deletion:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
return 0;
}

Write a program to print Transpose of a matrix.


#include <stdio.h>
int main() {
int matrix[10][10], transpose[10][10];
int rows, cols, i, j;
// Input rows and columns
printf("Enter the number of rows and columns of the matrix: ");
scanf("%d %d", &rows, &cols);
// Input matrix elements
printf("Enter elements of the matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Calculate transpose
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Print original matrix
printf("\nOriginal Matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
// Print transpose
printf("\nTranspose of the Matrix:\n");
for (i = 0; i < cols; i++) {
for (j = 0; j < rows; j++) {
printf("%d\t", transpose[i][j]);
}
printf("\n");
}
return 0;
}

Differentiate between a structure and Union.


Feature Structure (struct) Union (union)
Memory Allocates separate memory All members share the same
Allocation for each member. memory location.
Sum of sizes of all members Size is equal to the largest
Size
(plus possible padding). member.
All members can be Only one member can contain
Access
accessed independently. a meaningful value at a time.
Feature Structure (struct) Union (union)
Used when multiple data Used when data members are
Usage members are needed mutually exclusive (only one
simultaneously. is used at a time).
Can store name, age, and Can store either an int, float,
Example
marks together. or char one at a time.
struct Student { int id; char union Data { int i; float f;
Syntax
name[20]; }; char ch; };

Write a program to create structure for employee with


members like id, name and salary and display them in a
sorted order by name.
#include <stdio.h>
#include <string.h>
struct Employee {
int id;
char name[50];
float salary;
};
void sortByName(struct Employee emp[], int n) {
struct Employee temp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (strcmp(emp[i].name, emp[j].name) > 0) {
temp = emp[i];
emp[i] = emp[j];
emp[j] = temp;
}
}
}
}
int main() {
struct Employee emp[100];
int n;
printf("Enter the number of employees: ");
scanf("%d", &n);
// Input employee details
for (int i = 0; i < n; i++) {
printf("\nEnter details for employee %d\n", i + 1);
printf("ID: ");
scanf("%d", &emp[i].id);
printf("Name: ");
scanf(" %[^\n]", emp[i].name); // read string with spaces
printf("Salary: ");
scanf("%f", &emp[i].salary);
}
// Sort employees by name
sortByName(emp, n);
// Display sorted employee list
printf("\nEmployees sorted by name:\n");
printf("ID\tName\t\tSalary\n");
printf("-----------------------------------\n");
for (int i = 0; i < n; i++) {
printf("%d\t%-15s%.2f\n", emp[i].id, emp[i].name,
emp[i].salary);
}
return 0;
}
Explain dynamic memory allocation techniques in detail.
Dynamic memory allocation in C allows programs to allocate memory at
runtime (instead of compile time), providing flexibility in handling data
whose size might not be known in advance.

🔧 Dynamic Memory Allocation Techniques in C


The C standard library provides four primary functions for dynamic
memory allocation, declared in the header file stdlib.h:

1. malloc() – Memory Allocation


• Allocates a block of memory of specified size (in bytes).
• Returns a pointer to the first byte of the block.
• Does not initialize the memory (may contain garbage values).
int *ptr;
ptr = (int*) malloc(5 * sizeof(int)); // allocates memory for 5 integers
✅ Use when you need raw memory and plan to initialize it later.

2. calloc() – Contiguous Allocation


• Allocates memory for an array of elements and initializes all bytes
to zero.
• Takes two arguments: number of elements and size of each
element.
int *ptr;
ptr = (int*) calloc(5, sizeof(int)); // allocates and initializes memory for
5 integers
✅ Use when you want zero-initialized memory for an array.

3. realloc() – Reallocation
• Changes the size of previously allocated memory.
• Can expand or shrink the allocated memory block.
• Preserves existing data (up to the smaller of old or new size).
ptr = (int*) realloc(ptr, 10 * sizeof(int)); // resize memory to hold 10
integers
✅ Use when you need to resize a dynamic array based on runtime
conditions.

4. free() – Deallocation
• Frees dynamically allocated memory.
• Prevents memory leaks.
• After freeing, the pointer becomes a dangling pointer, so set it to
NULL.
free(ptr);
ptr = NULL;
✅ Always use when you're done with dynamically allocated memory.

📊 Comparison Table
Returns
Function Initialization Resizable NULL on Syntax
failure
malloc() No No Yes malloc(size_in_bytes)
calloc(num_elements,
calloc() Yes (to 0) No Yes
element_size)
Preserves
realloc() Yes Yes realloc(ptr, new_size)
data
free() N/A N/A N/A free(ptr)

🧠 Example Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n;
printf("Enter number of elements: ");
scanf("%d", &n);
arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory not allocated!\n");
return 1;
}
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
free(arr); // free memory
return 0;
}

Explain different functions used for File handling.


📄 File Handling Functions in C (5 Marks)
File handling in C allows reading from and writing to files using
standard library functions defined in stdio.h. Key functions include:

You might also like