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

Lab program

The document is a lab manual for a C programming course (MMC101) that includes various programming exercises. It covers topics such as creating a simple calculator using switch-case, implementing binary search algorithms, sorting numbers using bubble sort, and performing matrix multiplication with validation rules. Each exercise is presented with multiple variants demonstrating different coding approaches.

Uploaded by

Chaitra Nagaraj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views49 pages

Lab program

The document is a lab manual for a C programming course (MMC101) that includes various programming exercises. It covers topics such as creating a simple calculator using switch-case, implementing binary search algorithms, sorting numbers using bubble sort, and performing matrix multiplication with validation rules. Each exercise is presented with multiple variants demonstrating different coding approaches.

Uploaded by

Chaitra Nagaraj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 49

LAB MANUAL

MMC101 – Program and Problem-solving in C


ODD SEMESTER 2024-25

MR. JAFAR SADIQ A M


(Assistant Professor)
DEPARTMENT OF MCA
1. Write a C Program to make a Simple Calculator using switch-case
statements
1a) Variant 2: Using a switch-case statements for All Operations
#include <stdio.h>
int main() {
char op;
int a, b, res;

// Read the operator


printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);

// Read the two numbers


printf("Enter two operands: ");
scanf("%d %d", &a, &b);

// Define all four operations in the corresponding


// switch-case
switch (op) {
case '+':
res = a + b;
break;
case '-':
res = a - b;
break;
case '*':
res = a * b;
break;
case '/':
if(b!=0){
res = a / b;
}
Else{
Printf(“Zero Division Error!”);
}
break;
default:
printf("Error! Incorrect Operator Value\n");
}
Printf(“Result: %d \t”, res);
}

1b) Variant 1: Using Functions for Each Operation


#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) {


return a / b;
}

int main() {
char op;
int a, b, res;

// Read the operator


printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);

// Read the two numbers


printf("Enter two operands: ");
scanf("%d %d", &a, &b);

// Switch-case to call the appropriate function


switch (op) {
case '+':
res = add(a, b);
break;
case '-':
res = subtract(a, b);
break;
case '*':
res = multiply(a, b);
break;
case '/':
if (b != 0) {
res = divide(a, b);
} else {
printf("Error! Division by zero.\n");
return 1; // Exit the program if division by zero occurs
}
break;
default:
printf("Error! Incorrect Operator Value\n");
return 1;
}

// Display the result


printf("Result: %d\n", res);
return 0;
}

1c) Variant 2: Using a Single Function for All Operations

#include <stdio.h>

int calculate(int a, int b, char op) {


switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b != 0) {
return a / b;
} else {
printf("Error! Division by zero.\n");
return -1; // Return an error value
}
default:
printf("Error! Incorrect Operator Value\n");
return -1; // Return an error value
}
}

int main() {
char op;
int a, b, res;

// Read the operator


printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);

// Read the two numbers


printf("Enter two operands: ");
scanf("%d %d", &a, &b);

// Perform the calculation using the function


res = calculate(a, b, op);

if (res != -1) {
// Display the result
printf("Result: %d\n", res);
}

return 0;
}
2. Write a C program to implement the Binary Search algorithm on an
array of integers.
2a) Variant 1: Iterative binary search for Binary Search
#include <stdio.h>

// Function to perform Binary Search


int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Check if the target is at mid


if (arr[mid] == target)
return mid;

// If target is smaller, ignore the right half


if (arr[mid] > target)
right = mid - 1;

// If target is larger, ignore the left half


else
left = mid + 1;
}

// Target not found


return -1;
}

int main() {
int n, target, result;

// Input the size of the array


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

int arr[n];

// Input the sorted array


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

// Input the target element


printf("Enter the element to search for: ");
scanf("%d", &target);

// Call the binary search function


result = binarySearch(arr, n, target);

// Output the result


if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
}
else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}

2b) Variant 1: Using Recursion for Binary Search


#include <stdio.h>

// Function to perform Binary Search using recursion


int binarySearch(int arr[], int left, int right, int target) {
if (left > right)
return -1; // Target not found

int mid = left + (right - left) / 2;

// Check if the target is at mid


if (arr[mid] == target)
return mid;

// If target is smaller, search in the left half


if (arr[mid] > target)
return binarySearch(arr, left, mid - 1, target);

// If target is larger, search in the right half


return binarySearch(arr, mid + 1, right, target);
}

int main() {
int n, target, result;

// Input the size of the array


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

int arr[n];

// Input the sorted array


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

// Input the target element


printf("Enter the element to search for: ");
scanf("%d", &target);

// Call the recursive binary search function


result = binarySearch(arr, 0, n - 1, target);

// Output the result


if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}
2c) Variant 2: Using a Separate Function to Handle Input
#include <stdio.h>
// Function to perform Binary Search
int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Check if the target is at mid


if (arr[mid] == target)
return mid;

// If target is smaller, ignore the right half


if (arr[mid] > target)
right = mid - 1;

// If target is larger, ignore the left half


else
left = mid + 1;
}

// Target not found


return -1;
}
// Function to handle input and return the sorted array
void inputArray(int arr[], int n) {
printf("Enter %d elements in sorted order:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
}

int main() {
int n, target, result;

// Input the size of the array


printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];

// Input the sorted array using the helper function


inputArray(arr, n);

// Input the target element


printf("Enter the element to search for: ");
scanf("%d", &target);

// Call the binary search function


result = binarySearch(arr, n, target);

// Output the result


if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}

3. Write a program in C to sort a given set of N numbers using the Bubble


Sort algorithm.
3a) Variant 2: UnOptimized Bubble Sort with Early Termination.
#include <stdio.h>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

void printArray(int arr[], int n) {


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

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

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

bubbleSort(arr, n);

printf("Sorted array in ascending order: ");


printArray(arr, n);

return 0;
}

b) Variant 2: Optimized Bubble Sort with Early Termination


#include <stdio.h>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
int swapped = 0; // Flag to check if swapping occurred in this pass
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1;
}
}
// If no elements were swapped, array is already sorted
if (swapped == 0)
break;
}
}

void printArray(int arr[], int n) {


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

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

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

bubbleSort(arr, n);

printf("Sorted array in ascending order: ");


printArray(arr, n);

return 0;
}

c) Variant 3: Using a Function to Read the Array


#include <stdio.h>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

void printArray(int arr[], int n) {


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

void inputArray(int arr[], int n) {


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

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

int arr[n];

// Input the elements using a helper function


inputArray(arr, n);

bubbleSort(arr, n);

printf("Sorted array in ascending order: ");


printArray(arr, n);

return 0;
}

4. Write a C program to implement matrix multiplication and validate the


rules of matrix multiplication.
4a) Variant 1: Matrix Multiplication with static memory allocation
#include <stdio.h>
void inputMatrix(int matrix[10][10], int rows, int cols, const char *name) {
printf("Enter elements of matrix %s (%d x %d):\n", name, rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}

void displayMatrix(int matrix[10][10], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

void multiplyMatrices(int mat1[10][10], int mat2[10][10], int result[10][10], int r1, int c1, int c2) {
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
result[i][j] = 0; // Initialize result cell
for (int k = 0; k < c1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}

int main() {
int mat1[10][10], mat2[10][10], result[10][10];
int r1, c1, r2, c2;
// Input dimensions of matrices
printf("Enter rows and columns of first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and columns of second matrix: ");
scanf("%d%d", &r2, &c2);

// Validate multiplication rule


if (c1 != r2) {
printf("Matrix multiplication is not possible. Number of columns in the first matrix (%d) must equal
the number of rows in the second matrix (%d).\n", c1, r2);
return 0;
}

// Input matrices
inputMatrix(mat1, r1, c1, "A");
inputMatrix(mat2, r2, c2, "B");

// Perform multiplication
multiplyMatrices(mat1, mat2, result, r1, c1, c2);

// Display results
printf("Matrix A:\n");
displayMatrix(mat1, r1, c1);
printf("Matrix B:\n");
displayMatrix(mat2, r2, c2);
printf("Resultant Matrix (A x B):\n");
displayMatrix(result, r1, c2);

return 0;
}

4b) Variant 2: Matrix Multiplication with Dynamic Memory Allocation


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

void inputMatrix(int **matrix, int rows, int cols, const char *name) {
printf("Enter elements of matrix %s (%d x %d):\n", name, rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}

void displayMatrix(int **matrix, int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

void multiplyMatrices(int **mat1, int **mat2, int **result, int r1, int c1, int c2) {
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
result[i][j] = 0;
for (int k = 0; k < c1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}

int main() {
int **mat1, **mat2, **result;
int r1, c1, r2, c2;

// Input dimensions of matrices


printf("Enter rows and columns of first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and columns of second matrix: ");
scanf("%d%d", &r2, &c2);

// Validate multiplication rule


if (c1 != r2) {
printf("Matrix multiplication is not possible.\n");
return 0;
}

// Dynamic memory allocation for matrices


mat1 = (int **)malloc(r1 * sizeof(int *));
mat2 = (int **)malloc(r2 * sizeof(int *));
result = (int **)malloc(r1 * sizeof(int *));
for (int i = 0; i < r1; i++) {
mat1[i] = (int *)malloc(c1 * sizeof(int));
result[i] = (int *)malloc(c2 * sizeof(int));
}
for (int i = 0; i < r2; i++) {
mat2[i] = (int *)malloc(c2 * sizeof(int));
}

// Input matrices
inputMatrix(mat1, r1, c1, "A");
inputMatrix(mat2, r2, c2, "B");

// Perform multiplication
multiplyMatrices(mat1, mat2, result, r1, c1, c2);

// Display results
printf("Matrix A:\n");
displayMatrix(mat1, r1, c1);
printf("Matrix B:\n");
displayMatrix(mat2, r2, c2);
printf("Resultant Matrix (A x B):\n");
displayMatrix(result, r1, c2);

// Free dynamically allocated memory


for (int i = 0; i < r1; i++) {
free(mat1[i]);
free(result[i]);
}
for (int i = 0; i < r2; i++) {
free(mat2[i]);
}
free(mat1);
free(mat2);
free(result);
return 0;
}

4c) Variant 3: Matrix Multiplication with Function Pointer for Operation Customization
#include <stdio.h>

void inputMatrix(int matrix[10][10], int rows, int cols, const char *name) {
printf("Enter elements of matrix %s (%d x %d):\n", name, rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}

void displayMatrix(int matrix[10][10], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

void multiplyMatrices(int mat1[10][10], int mat2[10][10], int result[10][10], int r1, int c1, int c2, int
(*operation)(int, int)) {
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
result[i][j] = 0;
for (int k = 0; k < c1; k++) {
result[i][j] += operation(mat1[i][k], mat2[k][j]);
}
}
}
}

int multiplyOperation(int a, int b) {


return a * b;
}

int main() {
int mat1[10][10], mat2[10][10], result[10][10];
int r1, c1, r2, c2;

// Input dimensions of matrices


printf("Enter rows and columns of first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and columns of second matrix: ");
scanf("%d%d", &r2, &c2);

// Validate multiplication rule


if (c1 != r2) {
printf("Matrix multiplication is not possible.\n");
return 0;
}

// Input matrices
inputMatrix(mat1, r1, c1, "A");
inputMatrix(mat2, r2, c2, "B");

// Perform multiplication with custom operation


multiplyMatrices(mat1, mat2, result, r1, c1, c2, multiplyOperation);

// Display results
printf("Matrix A:\n");
displayMatrix(mat1, r1, c1);
printf("Matrix B:\n");
displayMatrix(mat2, r2, c2);
printf("Resultant Matrix (A x B):\n");
displayMatrix(result, r1, c2);

return 0;
}

5. An electricity board charges the following rates for the use of electricity:
for the first 200 units 80 paise per unit: for the next 100 units 90 paise
per unit: beyond 300 units Rs 1 per unit. All users are charged a
minimum of Rs. 100 as meter charge. If the total amount is more than
Rs 400, then an additional surcharge of 15% of total amount is charged.
Write a program to read the name of the user, number of units
consumed and print out the charges.
5a) Variant 1: Using Function for Surcharge Calculation
#include <stdio.h>
#include <string.h>

void main() {
int units;
float charge, surcharge = 0, amt, total_amt;
char name[25];

// Input customer details

printf("Enter the customer Name: ");


scanf("%s", name);

printf("Enter the units consumed by customer: ");


scanf("%d", &units);

// Calculate charge based on units consumed


if (units <= 200) {
charge = 0.80;
}
else if (units >= 200 && units <=300) {
charge = 0.90;
}
else {
charge = 1.00;
}

// Calculate amount before surcharge


amt = units * charge;

// Apply surcharge if applicable


if (amt > 400) {
surcharge = amt * 0.15; // 15% surcharge if the amount exceeds Rs 400
}
// Calculate total amount to be paid
total_amt = amt + surcharge;

// Display the bill


printf("\n\t\t\tElectricity Bill\n\n");
printf("Customer Name :\t%s\n", name);
printf("Units Consumed :\t%d\n", units);
printf("Amount Charges @Rs. %.2f per unit :\t%.2f\n", charge, amt);
printf("Surcharge Amount :\t%.2f\n", surcharge);
printf("Minimum Meter Charge Rs :\t100\n");
printf("Net Amount Paid By the Customer :\t%.2f\n", total_amt + 100); // Including minimum meter
charge

5b) Variant 2: Using Switch-Case for Charge Calculation


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

void main() {
int units;
float charge, surcharge = 0, amt, total_amt;
char name[25];

// Input customer details


printf("Enter the customer Name: ");
scanf("%s", name);

printf("Enter the units consumed by customer: ");


scanf("%d", &units);
// Calculate charge based on units consumed using switch-case
switch (units <= 200) {
case 1:
charge = 0.80;
break;
case 0:
switch (units >= 200 && units <= 300) {
case 1:
charge = 0.90;
break;
case 0:
charge = 1.00;
break;
}
}

// Calculate amount before surcharge


amt = units * charge;

// Apply surcharge if applicable


if (amt > 400) {
surcharge = amt * 0.15; // 15% surcharge if the amount exceeds Rs 400
}

// Calculate total amount to be paid


total_amt = amt + surcharge;

// Display the bill


printf("\n\t\t\tElectricity Bill\n\n");
printf("Customer Name :\t%s\n", name);
printf("Units Consumed :\t%d\n", units);
printf("Amount Charges @Rs. %.2f per unit :\t%.2f\n", charge, amt);
printf("Surcharge Amount :\t%.2f\n", surcharge);
printf("Minimum Meter Charge Rs :\t100\n");
printf("Net Amount Paid By the Customer :\t%.2f\n", total_amt + 100); // Including minimum meter
charge
}

5C) Variant 3: Using a While Loop for Repeated Bill Generation


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

void main() {
int units, continue_flag;
float charge, surcharge = 0, amt, total_amt;
char name[25];

do {
// Input customer details
printf("Enter the customer Name: ");
scanf("%s", name);

printf("Enter the units consumed by customer: ");


scanf("%d", &units);

// Calculate charge based on units consumed


if (units <= 200) {
charge = 0.80;
}
else if (units >= 200 && units <= 300) {
charge = 0.90;
}
else {
charge = 1.00;
}

// Calculate amount before surcharge


amt = units * charge;

// Apply surcharge if applicable


if (amt > 400) {
surcharge = amt * 0.15; // 15% surcharge if the amount exceeds Rs 400
}

// Calculate total amount to be paid


total_amt = amt + surcharge;

// Display the bill


printf("\n\t\t\tElectricity Bill\n\n");
printf("Customer Name :\t%s\n", name);
printf("Units Consumed :\t%d\n", units);
printf("Amount Charges @Rs. %.2f per unit :\t%.2f\n", charge, amt);
printf("Surcharge Amount :\t%.2f\n", surcharge);
printf("Minimum Meter Charge Rs :\t100\n");
printf("Net Amount Paid By the Customer :\t%.2f\n", total_amt + 100); // Including minimum
meter charge

// Ask if user wants to calculate bill for another customer


printf("\nDo you want to generate another bill? (1 for Yes, 0 for No): ");
scanf("%d", &continue_flag);

} while (continue_flag == 1);


}

6. Write c program functions to implement string operations such as compare,


concatenate, and find string length. Use the parameter passing techniques.
6a) Variant 1: Using Pointer for String Comparison and Concatenation
#include <stdio.h>
#include <string.h>

// Function to compare two strings


// Parameter passing by value
int compareStrings(char str1[], char str2[]) {
if (strcmp(str1, str2) == 0) {
return 0; // Strings are equal
}
return -1; // Strings are not equal
}

// Function to concatenate two strings


// Parameter passing by reference (using pointers)
void concatenateStrings(char *str1, const char *str2) {
strcat(str1, str2); // Concatenate str2 to str1
}

// Function to find the length of a string


// Parameter passing by reference (using pointers)
int stringLength(const char *str) {
return strlen(str); // Returns the length of the string
}
int main() {
char str1[200], str2[100];

// Input two strings


printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = 0; // Remove newline character from the input

printf("Enter second string: ");


fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = 0; // Remove newline character from the input

// Compare strings
if (compareStrings(str1, str2) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}

// Concatenate strings
concatenateStrings(str1, str2);
printf("Concatenated string: %s\n", str1);

// Find the length of the concatenated string


printf("Length of the concatenated string: %d\n", stringLength(str1));

return 0;
}
6b) Variant 2: Using Structs for String Operations
#include <stdio.h>
#include <string.h>

typedef struct {
char str1[200];
char str2[100];
} StringOperations;

// Function to compare two strings


int compareStrings(const StringOperations *strOps) {
if (strcmp(strOps->str1, strOps->str2) == 0) {
return 0; // Strings are equal
}
return -1; // Strings are not equal
}

// Function to concatenate two strings


void concatenateStrings(StringOperations *strOps) {
strcat(strOps->str1, strOps->str2);
}

// Function to find the length of the first string


int stringLength(const StringOperations *strOps) {
return strlen(strOps->str1);
}
int main() {
StringOperations strOps;

// Input two strings


printf("Enter first string: ");
fgets(strOps.str1, sizeof(strOps.str1), stdin);
strOps.str1[strcspn(strOps.str1, "\n")] = 0;

printf("Enter second string: ");


fgets(strOps.str2, sizeof(strOps.str2), stdin);
strOps.str2[strcspn(strOps.str2, "\n")] = 0;

// Compare strings
if (compareStrings(&strOps) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}

// Concatenate strings
concatenateStrings(&strOps);
printf("Concatenated string: %s\n", strOps.str1);

// Find the length of the concatenated string


printf("Length of the concatenated string: %d\n", stringLength(&strOps));

return 0;
}
6c) Variant 3: Using Dynamic Memory Allocation for String Inputs
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Function to compare two strings


int compareStrings(const char *str1, const char *str2) {
if (strcmp(str1, str2) == 0) {
return 0; // Strings are equal
}
return -1; // Strings are not equal
}

// Function to concatenate two strings


char* concatenateStrings(char *str1, const char *str2) {
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
char *result = (char *)malloc(len1 + len2 + 1); // Allocate memory for the result

if (result == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}

strcpy(result, str1); // Copy str1 into result


strcat(result, str2); // Append str2 to result
return result; // Return the concatenated string
}

// Function to find the length of a string


int stringLength(const char *str) {
return strlen(str); // Returns the length of the string
}

int main() {
char *str1, *str2;
size_t size1 = 200, size2 = 100;

// Allocate memory for strings


str1 = (char *)malloc(size1 * sizeof(char));
str2 = (char *)malloc(size2 * sizeof(char));

if (str1 == NULL || str2 == NULL) {


printf("Memory allocation failed.\n");
exit(1);
}

// Input two strings


printf("Enter first string: ");
fgets(str1, size1, stdin);
str1[strcspn(str1, "\n")] = 0;

printf("Enter second string: ");


fgets(str2, size2, stdin);
str2[strcspn(str2, "\n")] = 0;
// Compare strings
if (compareStrings(str1, str2) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}

// Concatenate strings
char *concatenated = concatenateStrings(str1, str2);
printf("Concatenated string: %s\n", concatenated);

// Find the length of the concatenated string


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

// Free allocated memory


free(str1);
free(str2);
free(concatenated);

return 0;
}
7. Write a c program to implement structures to read, write and compute
average- marks of the students, list the students scoring above and below the
average marks for a class of N students.
7a) Variant 1: Using Dynamic Memory Allocation for Student Records
#include <stdio.h>
struct Student {
char name[50];
int marks;
};

void computeAverage(struct Student students[], int n) {


int totalMarks = 0;
for (int i = 0; i < n; i++) {
totalMarks += students[i].marks;
}
float average = (float)totalMarks / n;
printf("\nAverage Marks: %.2f\n", average);

printf("\nStudents scoring above average:\n");


for (int i = 0; i < n; i++) {
if (students[i].marks > average) {
printf("%s: %d\n", students[i].name, students[i].marks);
}
}

printf("\nStudents scoring below average:\n");


for (int i = 0; i < n; i++) {
if (students[i].marks < average) {
printf("%s: %d\n", students[i].name, students[i].marks);
}
}
}

int main() {
int n;

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


scanf("%d", &n);

struct Student students[n];

// Reading student information


for (int i = 0; i < n; i++) {
printf("\nEnter the name of student %d: ", i + 1);
scanf(" %[^\n]%*c", students[i].name); // To read full name with spaces
printf("Enter the marks of %s: ", students[i].name);
scanf("%d", &students[i].marks);
}

// Compute average and list students


computeAverage(students, n);

return 0;
}
7b) Variant 2: Using Linked List to Store Student Records
#include <stdio.h>
#include <stdlib.h>

struct Student {
char name[50];
int marks;
struct Student *next;
};

void computeAverage(struct Student *head, int n) {


int totalMarks = 0;
struct Student *current = head;

while (current != NULL) {


totalMarks += current->marks;
current = current->next;
}

float average = (float)totalMarks / n;


printf("\nAverage Marks: %.2f\n", average);

printf("\nStudents scoring above average:\n");


current = head;
while (current != NULL) {
if (current->marks > average) {
printf("%s: %d\n", current->name, current->marks);
}
current = current->next;
}

printf("\nStudents scoring below average:\n");


current = head;
while (current != NULL) {
if (current->marks < average) {
printf("%s: %d\n", current->name, current->marks);
}
current = current->next;
}
}

int main() {
int n;

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


scanf("%d", &n);

struct Student *head = NULL, *temp, *newStudent;

// Reading student information


for (int i = 0; i < n; i++) {
newStudent = (struct Student *)malloc(sizeof(struct Student));
if (newStudent == NULL) {
printf("Memory allocation failed.\n");
return -1;
}

printf("\nEnter the name of student %d: ", i + 1);


scanf(" %[^\n]%*c", newStudent->name); // To read full name with spaces
printf("Enter the marks of %s: ", newStudent->name);
scanf("%d", &newStudent->marks);
newStudent->next = NULL;

if (head == NULL) {
head = newStudent;
} else {
temp->next = newStudent;
}
temp = newStudent;
}

// Compute average and list students


computeAverage(head, n);

// Free allocated memory


struct Student *current = head;
while (current != NULL) {
struct Student *temp = current;
current = current->next;
free(temp);
}

return 0;
}
7c) Variant 3: Using Separate Functions for Student Input and Output
#include <stdio.h>
struct Student {
char name[50];
int marks;
};

void getStudentInfo(struct Student students[], int n) {


for (int i = 0; i < n; i++) {
printf("\nEnter the name of student %d: ", i + 1);
scanf(" %[^\n]%*c", students[i].name); // To read full name with spaces
printf("Enter the marks of %s: ", students[i].name);
scanf("%d", &students[i].marks);
}
}

void printStudentResults(struct Student students[], int n, float average) {


printf("\nStudents scoring above average:\n");
for (int i = 0; i < n; i++) {
if (students[i].marks > average) {
printf("%s: %d\n", students[i].name, students[i].marks);
}
}

printf("\nStudents scoring below average:\n");


for (int i = 0; i < n; i++) {
if (students[i].marks < average) {
printf("%s: %d\n", students[i].name, students[i].marks);
}
}
}

float computeAverage(struct Student students[], int n) {


int totalMarks = 0;
for (int i = 0; i < n; i++) {
totalMarks += students[i].marks;
}
return (float)totalMarks / n;
}

int main() {
int n;

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


scanf("%d", &n);

struct Student students[n];

// Reading student information


getStudentInfo(students, n);

// Compute average
float average = computeAverage(students, n);

// Output results
printf("\nAverage Marks: %.2f\n", average);
printStudentResults(students, n, average);
return 0;
}

8. Write a C program to copy a text file to another, read both the input file
name and target file name.
8a)Variant 1: Using fread and fwrite for Binary File Copying
#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *sourceFile, *targetFile;
char sourceFileName[100], targetFileName[100];
char ch;

// Prompt the user to enter source and target file names


printf("Enter the source file name: ");
scanf("%s", sourceFileName);
printf("Enter the target file name: ");
scanf("%s", targetFileName);

// Open the source file in read mode


sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL) {
printf("Error: Could not open the source file %s\n", sourceFileName);
exit(1); // Exit if source file doesn't exist
}

// Open the target file in write mode


targetFile = fopen(targetFileName, "w");
if (targetFile == NULL) {
printf("Error: Could not open the target file %s\n", targetFileName);
fclose(sourceFile); // Close the source file before exiting
exit(1);
}

// Copy the contents of the source file to the target file


while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, targetFile);
}

printf("File content copied successfully from %s to %s\n", sourceFileName, targetFileName);

// Close both files


fclose(sourceFile);
fclose(targetFile);

return 0;
}

8b) Variant 2: Using fseek to Copy from Specific Positions in Files


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

int main() {
FILE *sourceFile, *targetFile;
char sourceFileName[100], targetFileName[100];
char ch;
long position;

// Prompt the user to enter source and target file names


printf("Enter the source file name: ");
scanf("%s", sourceFileName);
printf("Enter the target file name: ");
scanf("%s", targetFileName);

// Open the source file in read mode


sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL) {
printf("Error: Could not open the source file %s\n", sourceFileName);
exit(1); // Exit if source file doesn't exist
}

// Open the target file in write mode


targetFile = fopen(targetFileName, "w");
if (targetFile == NULL) {
printf("Error: Could not open the target file %s\n", targetFileName);
fclose(sourceFile); // Close the source file before exiting
exit(1);
}

// Prompt the user to enter the starting position in the source file
printf("Enter the position to start copying from (in bytes): ");
scanf("%ld", &position);

// Move to the specified position in the source file


fseek(sourceFile, position, SEEK_SET);

// Copy the contents from the current position in the source file to the target file
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, targetFile);
}
printf("File content copied successfully from %s to %s starting from position %ld\n", sourceFileName,
targetFileName, position);

// Close both files


fclose(sourceFile);
fclose(targetFile);

return 0;
}

8c) Variant 3: Using rename to Copy File


#include <stdio.h>
#include <stdlib.h>
int main() {
char sourceFileName[100], targetFileName[100];

// Prompt the user to enter source and target file names


printf("Enter the source file name: ");
scanf("%s", sourceFileName);
printf("Enter the target file name: ");
scanf("%s", targetFileName);

// Attempt to rename (copy) the file


if (rename(sourceFileName, targetFileName) == 0) {
printf("File content copied successfully from %s to %s\n", sourceFileName, targetFileName);
} else {
printf("Error: Could not copy the file from %s to %s\n", sourceFileName, targetFileName);
exit(1);
}
return 0;
}

You might also like