0% found this document useful (0 votes)
4 views14 pages

SWAYAM DAY10PTC

The document contains multiple C programming examples that demonstrate various concepts such as dynamic memory allocation, string manipulation, function pointers, and sorting algorithms. Each example includes code snippets for tasks like finding the largest element in an array, calculating string length, reversing words in a sentence, and implementing a simple calculator. The document serves as a practical guide for learning and applying C programming techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views14 pages

SWAYAM DAY10PTC

The document contains multiple C programming examples that demonstrate various concepts such as dynamic memory allocation, string manipulation, function pointers, and sorting algorithms. Each example includes code snippets for tasks like finding the largest element in an array, calculating string length, reversing words in a sentence, and implementing a simple calculator. The document serves as a practical guide for learning and applying C programming techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1. Write a program in C to find the largest element using Dynamic Memory Allocation.

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

int main() {
int n;

printf("Enter the number of elements: ");


scanf("%d", &n);

// Dynamically allocate memory for the array


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

if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

printf("Enter the elements:\n");


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

int largest = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}

printf("The largest element is: %d\n", largest);

// Free the dynamically allocated memory


free(arr);

return 0;
}

2. Write a program in C to calculate the length of a string using a pointer.


#include <stdio.h>

int string_length(char *str) {


int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}

int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str);

int length = string_length(str);

printf("Length of the string: %d\n", length);

return 0;
}

3. Write a program to dynamically allocate, initialize, and free a 3D array using pointers.
#include <stdio.h>
#include <stdlib.h>

int main() {
int x, y, z;

printf("Enter dimensions (x, y, z): ");


scanf("%d %d %d", &x, &y, &z);

// Allocate memory for the 3D array


int ***arr = (int***)malloc(x * sizeof(int**));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

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


arr[i] = (int**)malloc(y * sizeof(int*));
if (arr[i] == NULL) {
printf("Memory allocation failed!\n");
// Free previously allocated memory
for (int j = 0; j < i; j++) {
free(arr[j]);
}
free(arr);
return 1;
}

for (int j = 0; j < y; j++) {


arr[i][j] = (int*)malloc(z * sizeof(int));
if (arr[i][j] == NULL) {
printf("Memory allocation failed!\n");
// Free previously allocated memory
for (int k = 0; k < j; k++) {
free(arr[i][k]);
}
free(arr[i]);
for (int k = 0; k < i; k++) {
free(arr[k]);
}
free(arr);
return 1;
}
}
}

// Initialize the 3D array (example: with increasing values)


int value = 1;
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
for (int k = 0; k < z; k++) {
arr[i][j][k] = value++;
}
}
}

// Access and print elements of the 3D array


// ...

// Free the dynamically allocated memory


for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
free(arr[i][j]);
}
free(arr[i]);
}
free(arr);
return 0;
}

4. Implement a function using pointer-to-pointer to reverse the words in a sentence without


using additional arrays.
#include <stdio.h>
#include <string.h>

void reverse_words(char **str) {


char *start = *str;
char *end = *str + strlen(*str) - 1;

while (start < end) {


char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}

start = *str;
while (*start) {
while (*start && *start != ' ') {
start++;
}

end = start - 1;
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}

while (*start && *start == ' ') {


start++;
}
}
}

int main() {
char str[100] = "This is a sentence";

printf("Original sentence: %s\n", str);

reverse_words(&str);
printf("Reversed sentence: %s\n", str);

return 0;
}

5. Write a program that uses a function pointer array to implement a simple calculator
(addition, subtraction, multiplication, division).
#include <stdio.h>

int add(int a, int b) {


return a + b;
}

int subtract(int a, int b) {


return a - b;
}

int multiply(int a, int b) {


return a * b;
}

int divide(int a, int b) {


if (b == 0) {
printf("Error: Division by zero\n");
return 0;
}
return a / b;
}

int main() {
int (*operations[4])(int, int) = {add, subtract, multiply, divide};
int choice, num1, num2, result;

printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
printf("Enter your choice: ");
scanf("%d", &choice);

printf("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

if (choice >= 1 && choice <= 4) {


result = operations[choice - 1](num1, num2);
printf("Result: %d\n", result);
} else {
printf("Invalid choice\n");
}

return 0;
}

6. Write a program to sort an array of integers using a generic comparison function and a
function pointer.
#include <stdio.h>

int compare_ints(const void *a, const void *b) {


return (*(int*)a - *(int*)b);
}

void bubble_sort(void *arr, int size, size_t element_size, int (*compare)(const void*, const
void*)) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (compare((char*)arr + j * element_size, (char*)arr + (j + 1) * element_size) > 0) {
// Swap elements
void *temp = malloc(element_size);
memcpy(temp, (char*)arr + j * element_size, element_size);
memcpy((char*)arr + j * element_size, (char*)arr + (j + 1) * element_size,
element_size);
memcpy((char*)arr + (j + 1) * element_size, temp, element_size);
free(temp);
}
}
}
}

int main() {
int arr[] = {5, 2, 9, 1, 5};
int size = sizeof(arr) / sizeof(arr[0]);

bubble_sort(arr, size, sizeof(int), compare_ints);


printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

7. Write a program that uses void pointers to implement a generic sort function for arrays of
different data types (int, float, char, etc.).

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int compare_ints(const void *a, const void *b) {

return (*(int*)a - *(int*)b);

int compare_floats(const void *a, const void *b) {

return (*(float*)a > *(float*)b) - (*(float*)a < *(float*)b);

int compare_chars(const void *a, const void *b) {

return *(char*)a - *(char*)b;

void bubble_sort(void *arr, int size, size_t element_size, int (*compare)(const void*, const
void*)) {

for (int i = 0; i < size - 1; i++) {

for (int j = 0; j < size - i - 1; j++) {

if (compare((char*)arr + j * element_size, (char*)arr + (j + 1) * element_size) > 0) {

void *temp = malloc(element_size);

memcpy(temp, (char*)arr + j * element_size, element_size);


memcpy((char*)arr + j * element_size, (char*)arr + (j + 1) * element_size,
element_size);

memcpy((char*)arr + (j + 1) * element_size, temp, element_size);

free(temp);

int main() {

int int_arr[] = {5, 2, 9, 1, 5};

float float_arr[] = {3.14, 1.57, 2.71};

char char_arr[] = "hello";

bubble_sort(int_arr, sizeof(int_arr) / sizeof(int_arr[0]), sizeof(int), compare_ints);

bubble_sort(float_arr, sizeof(float_arr) / sizeof(float_arr[0]), sizeof(float), compare_floats);

bubble_sort(char_arr, strlen(char_arr), sizeof(char), compare_chars);

// Print sorted arrays

// ...

return 0;

8.Write a program that demonstrates the use of function pointers to traverse and execute multiple
algorithms on the same data set (e.g., finding the sum, average, and maximum of an array).

#include <stdio.h>
int sum(int arr[], int size) {
int total = 0;
for (int i = 0; i < size; i++) {
total += arr[i];
}
return total;
}

float average(int arr[], int size) {


return (float)sum(arr, size) / size;
}

int find_max(int arr[], int size) {


int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}

int main() {
int arr[] = {10, 5, 20, 3, 8};
int size = sizeof(arr) / sizeof(arr[0]);

int (*operations[])(int[], int) = {sum, average, find_max};

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


if (i == 1) { // Average needs to be printed as a float
printf("Average: %.2f\n", operations[i](arr, size));
} else {
printf("%s: %d\n", i == 0 ? "Sum" : "Max", operations[i](arr, size));
}
}

return 0;
}

9. Design a small library management system where function pointers are used to perform
operations like adding a book, searching for a

book, and deleting a book.

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

#include <string.h>

// Structure to represent a book

typedef struct {

char title[100];

char author[50];

int year;

} Book;

// Function pointers for library operations

void (*library_operation)(Book *books, int *num_books);

// Library operations

void add_book(Book *books, int *num_books) {

// ... (implementation to add a book)

void search_book(Book *books, int num_books) {

// ... (implementation to search for a book)

void delete_book(Book *books, int *num_books) {

// ... (implementation to delete a book)

int main() {

Book library[100];

int num_books = 0;

library_operation = add_book; // Set the initial operation to add_book


library_operation(library, &num_books);

library_operation = search_book;

library_operation(library, num_books);

// ... (continue with other operations)

return 0;

10. Write a program that uses a function pointer to implement a state machine, simulating a traffic
light system (Red, Green, Yellow).

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// Structure to represent a book

typedef struct {

char title[100];
char author[50];

int year;

} Book;

// Function pointers for library operations

void (*library_operation)(Book *books, int *num_books);

// Library operations

void add_book(Book *books, int *num_books) {

// ... (implementation to add a book)

void search_book(Book *books, int num_books) {

// ... (implementation to search for a book)

void delete_book(Book *books, int *num_books) {

// ... (implementation to delete a book)

int main() {

Book library[100];

int num_books = 0;

library_operation = add_book; // Set the initial operation to add_book

library_operation(library, &num_books);

library_operation = search_book;

library_operation(library, num_books);

// ... (continue with other operations)


return 0;

11. Write a program to dynamically allocate memory for a string, read user input, and reverse the
string.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main() {

char *str;

int length;

printf("Enter the string: ");

scanf("%s", &length); // Get length of input

str = (char *)malloc((length + 1) * sizeof(char)); // Allocate memory for string

if (str == NULL) {

printf("Memory allocation failed!\n");

return 1;

scanf("%s", str); // Read the string

// Reverse the string

for (int i = 0, j = strlen(str) - 1; i < j; i++, j--) {

char temp = str[i];


str[i] = str[j];

str[j] = temp;

printf("Reversed string: %s\n", str);

free(str); // Free allocated memory

return 0;

You might also like