0% found this document useful (0 votes)
13 views33 pages

C Programming Exercises and Solutions

The document lists various programming tasks and examples in C, including arithmetic operations, control structures, recursion, and file handling. It covers topics such as finding roots of quadratic equations, checking for Armstrong and Magic numbers, and implementing sorting and searching algorithms. Additionally, it includes programs for converting between number systems and generating patterns like Pascal's Triangle and pyramids of numbers.

Uploaded by

rrmanziltv
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)
13 views33 pages

C Programming Exercises and Solutions

The document lists various programming tasks and examples in C, including arithmetic operations, control structures, recursion, and file handling. It covers topics such as finding roots of quadratic equations, checking for Armstrong and Magic numbers, and implementing sorting and searching algorithms. Additionally, it includes programs for converting between number systems and generating patterns like Pascal's Triangle and pyramids of numbers.

Uploaded by

rrmanziltv
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

LIST OF PROGRAMS

1. Write program using Arithmetic, Logical, Bitwise and Ternary operators.


2. Implement control structures, find roots of quadratic equation.
3. Find reverse of a given number.

4. Check if a number is Armstrong or not using functions.


5. Check if the given number is Magic number or not.
6. Find sinx and cosx values using series expansion implementing functions in C.

7. Program to implement Pascal Triangle.


8. Program to implement Pyramid of numbers.
9. Program to implement and two loop patterns.

10. Write a program to convert Binary to Decimal.


11. Write a program to convert Decimal to Hexadecimal.
12. Write a program to convert Decimal to Octal.

13. Find factorial of a number using recursion in C.


14. Find fibonacci of a number using recursion in C.
15. Find gcd using recursion in C.

16. Reverse an array in C.


17. Remove the duplicates in the array in C.
18. Program to implement matrix multiplication in C.

19. Implement Bubble sort in C.


20. Implement Selection sort in C.
21. Implement Linear search in C.

22. Implement Binary search in C.


23. Implement Linear search in C using recursion.
24. Implement Binary search in C using recursion.

25. Program to swap two numbers using pointers.


26. Program to implement matrix addition using pointers.
27. Program to illustrate usage of malloc(), realloc() and free() functions.

28. Implement string handling functions using string library.


29. Implement string reverse without using string functions.
30. Implement string to lowercase and vice versa with using string functions.

31. Program to implement Student information using structures.


32. Program to implement self-referential structure in C.
33. Implement union and typedef in a program in C.

34. Find the number of characters, words, and lines of a given text file.
35. Program to merge two files into a third file.
36. Use file handling to print student memo.
PROGRAMS

1. Write program using Arithmetic, Logical, Bitwise and Ternary operators.


#include <stdio.h>
int main() {
int a = 10, b = 5;

// Arithmetic Operators
int sum = a + b;
int diff = a - b;
int prod = a * b;
int div = a / b;
int mod = a % b;

// Logical Operators
int logical_and = (a > b) && (b > 0);
int logical_or = (a < b) || (b > 0);
int logical_not = !(a == b);

// Bitwise Operators
int bit_and = a & b;
int bit_or = a | b;
int bit_xor = a ^ b;
int bit_left = a << 1;
int bit_right = a >> 1;

// Ternary Operator
int max = (a > b) ? a : b;

// Display
printf("\n--- Arithmetic Operators ---\n");
printf("Sum = %d\n", sum);
printf("Difference = %d\n", diff);
printf("Product = %d\n", prod);
printf("Division = %d\n", div);
printf("Modulus = %d\n", mod);

printf("\n--- Logical Operators ---\n");


printf("(a > b) && (b > 0) = %d\n", logical_and);
printf("(a < b) || (b > 0) = %d\n", logical_or);
printf("!(a == b) = %d\n", logical_not);

printf("\n--- Bitwise Operators ---\n");


printf("a & b = %d\n", bit_and);
printf("a | b = %d\n", bit_or);
printf("a ^ b = %d\n", bit_xor);
printf("a << 1 = %d\n", bit_left);
printf("a >> 1 = %d\n", bit_right);

printf("\n--- Ternary Operator ---\n");


printf("Max of a and b = %d\n", max);
return 0;
}
OUTPUT:
--- Arithmetic Operators ---
Sum = 15
Difference = 5
Product = 50
Division = 2
Modulus = 0

--- Logical Operators ---


(a > b) && (b > 0) = 1
(a < b) || (b > 0) = 1
!(a == b) = 1

--- Bitwise Operators ---


a&b=0
a | b = 15
a ^ b = 15
a << 1 = 20
a >> 1 = 5

--- Ternary Operator ---


Max of a and b = 10

2. Implement control structures, find roots of quadratic equation.


#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, d, root1, root2;
printf("Enter coefficients a, b and c: ");
scanf("%f", &a);
scanf("%f", &b);
scanf("%f", &c);

// Calculate discriminant
d = (b * b) - (4 * a * c);
// Control Structures (if-else)
if (d > 0) {
root1 = (-b + sqrt(d)) / (2 * a);
root2 = (-b - sqrt(d)) / (2 * a);
printf("\nRoots are REAL and DISTINCT\n");
printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
}
else if (d == 0) {
root1 = root2 = -b / (2 * a);
printf("\nRoots are REAL and EQUAL\n");
printf("Root = %.2f\n", root1);
}
else {
float realPart = -b / (2 * a);
float imagPart = sqrt(-d) / (2 * a);
printf("\nRoots are IMAGINARY\n");
printf("Root 1 = %.2f + %.2fi\n", realPart, imagPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imagPart);
}
return 0;
}
OUTPUT:
a=1 b = -3 c = 2
Roots are REAL and DISTINCT
Root 1 = 2.00
Root 2 = 1.00

3. Find reverse of a given number.


#include <stdio.h>
int main() {
int num, reversed = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);

while (num != 0) {
remainder = num % 10; // extract last digit
reversed = reversed * 10 + remainder; // build reversed number
num = num / 10; // remove last digit
}
printf("Reversed number = %d\n", reversed);
return 0;
}
OUTPUT:
Enter a number: 12345
Reversed number = 54321

4. Check if a number is Armstrong or not using functions.


#include <stdio.h>
#include <math.h>
int isArmstrong(int num) {
int original = num, digits = 0, sum = 0;

// Count digits
while (num != 0) {
num /= 10;
digits++;
}
num = original;
// Compute sum of powers
while (num != 0) {
int digit = num % 10;
sum += pow(digit, digits);
num /= 10;
}

return (sum == original); // return 1 if Armstrong, else 0


}

int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (isArmstrong(number))
printf("%d is an Armstrong number.\n", number);
else
printf("%d is NOT an Armstrong number.\n", number);
return 0;
}
OUTPUT:
Enter a number: 153
153 is an Armstrong number.

5. Check if the given number is Magic number or not.


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

// Function to compute sum of digits


int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n = n / 10;
}
return sum;
}

int main() {
int num, temp;

printf("Enter a number: ");


scanf("%d", &num);
temp = num;

// Keep summing digits until one digit remains


while (temp > 9) {
temp = sumOfDigits(temp);
}
if (temp == 1)
printf("%d is a Magic Number.\n", num);
else
printf("%d is NOT a Magic Number.\n", num);
return 0;
}
OUTPUT:
Enter a number: 172
172 is a Magic Number.

6. Find sinx and cosx values using series expansion implementing functions in C.
#include <stdio.h>

// Function to calculate factorial


long double fact(int n) {
long double f = 1;
for (int i = 1; i <= n; i++) {
f *= i;
}
return f;
}

// Function to calculate sin(x) using series


long double sine(long double x) {
long double sum = 0;
int sign = 1;
for (int i = 1; i <= 10; i += 2) { // first 5 terms
sum += sign * ( (long double) (pow(x, i) / fact(i)) );
sign = -sign; // alternate signs
}
return sum;
}

// Function to calculate cos(x) using series


long double cosine(long double x) {
long double sum = 0;
int sign = 1;
for (int i = 0; i <= 10; i += 2) { // first 6 terms
sum += sign * ( (long double) (pow(x, i) / fact(i)) );
sign = -sign;
}
return sum;
}

int main() {
long double x;
printf("Enter x in radians: ");
scanf("%Lf", &x);
printf("\nUsing Series Expansion:\n");
printf("sin(%.4Lf) = %.10Lf\n", x, sine(x));
printf("cos(%.4Lf) = %.10Lf\n", x, cosine(x));

return 0;
}
OUTPUT:
Enter x in radians: 1.5708
Using Series Expansion:
sin(1.5708) = 0.9999996829
cos(1.5708) = 0.0007963267

7. Program to implement Pascal Triangle.


#include <stdio.h>
// Function to calculate nCr (binomial coefficient)
int nCr(int n, int r) {
int num = 1, den = 1;

for (int i = 1; i <= r; i++) {


num = num * (n - i + 1);
den = den * i;
}
return num / den;
}

int main() {
int rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("\nPascal Triangle:\n");

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


// Print spaces for alignment
for (int j = 0; j < rows - i; j++) {
printf(" ");
}

// Print numbers using nCr


for (int j = 0; j <= i; j++) {
printf("%d ", nCr(i, j));
}
printf("\n");
}
return 0;
}

OUTPUT:
Enter number of rows: 5
1
11
121
1331
14641

8. Program to implement Pyramid of numbers.


#include <stdio.h>
int main() {
int rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("\nNumber Pyramid:\n");
for (int i = 1; i <= rows; i++) {

// Print spaces
for (int s = 1; s <= rows - i; s++) {
printf(" ");
}
// Print numbers
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
OUTPUT:
Enter number of rows: 5
1
12
123
1234
12345

9. Program to implement and two loop patterns.


(a)
#include <stdio.h>
int main() {
int rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("\nPattern 1:\n");
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
OUTPUT:
Enter number of rows:5
Pattern 1:
1
12
123
124
12345

(b)
#include <stdio.h>
int main() {
int rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("\nPattern 2:\n");
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
OUTPUT:
Enter number of rows:5
Pattern 2:
*
**
***
****
*****

10. Write a program to convert Binary to Decimal.


#include <stdio.h>
#include <math.h>
int main() {
long long binary;
int decimal = 0, base = 1, remainder;
printf("Enter a binary number: ");
scanf("%lld", &binary);
long long temp = binary;

while (temp > 0) {


remainder = temp % 10; // extract last digit
decimal += remainder * base;
base *= 2; // base changes to 2^n
temp /= 10; // remove last digit
}
printf("Decimal value = %d\n", decimal);
return 0;
}
OUTPUT:
Enter a binary number: 1011
Decimal value = 11

11. Write a program to convert Decimal to Hexadecimal.


#include <stdio.h>
int main() {
long long decimal;
char hex[100];
int index = 0;
printf("Enter a decimal number: ");
scanf("%lld", &decimal);

// If the number is zero


if (decimal == 0) {
printf("Hexadecimal: 0\n");
return 0;
}

long long temp = decimal;


// Convert using repeated division by 16
while (temp > 0) {
int rem = temp % 16;

if (rem < 10)


hex[index++] = rem + '0';
else
hex[index++] = rem - 10 + 'A';
temp /= 16;
}

// Print the hex string in reverse


printf("Hexadecimal: ");
for (int i = index - 1; i >= 0; i--) {
putchar(hex[i]);
}
printf("\n");
return 0;
}
OUTPUT:
Enter a decimal number: 438
Hexadecimal: 1B6
12. Write a program to convert Decimal to Octal.
#include <stdio.h>
int main() {
int decimal, octal[32], i = 0;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
int temp = decimal;

// Convert decimal to octal


if (decimal == 0) {
printf("Octal value = 0\n");
return 0;
}
while (temp > 0) {
octal[i] = temp % 8;
temp /= 8;
i++;
}

// Print octal number in reverse


printf("Octal value = ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", octal[j]);
}
printf("\n");
return 0;
}
OUTPUT:
Enter a decimal number: 25
Octal value = 31

13. Find factorial of a number using recursion in C.


#include <stdio.h>
// Recursive function to calculate factorial
long long factorial(int n) {
if (n == 0 || n == 1) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}

int main() {
int number;
long long result;
printf("Enter a number: ");
scanf("%d", &number);
if (number < 0)
printf("Factorial is not defined for negative numbers.\n");
else {
result = factorial(number);
printf("Factorial of %d is %lld\n", number, result);
}
return 0;
}
OUTPUT:
Enter a number: 5
Factorial of 5 is 120

14. Find fibonacci of a number using recursion in C.


#include <stdio.h>
// Recursive function to find nth Fibonacci number
int fibonacci(int n) {
if (n == 0) // Base case
return 0;
else if (n == 1) // Base case
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}

int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}
OUTPUT:
Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8

15. Find gcd using recursion in C.


#include <stdio.h>
// Recursive function to find GCD using Euclid's algorithm
int gcd(int a, int b) {
if (b == 0) // Base case
return a;
else
return gcd(b, a % b); // Recursive call
}

int main() {
int num1, num2, result;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
result = gcd(num1, num2);
printf("GCD of %d and %d is %d\n", num1, num2, result);
return 0;
}
OUTPUT:
Enter two numbers: 24 36
GCD of 24 and 36 is 12

16. Reverse an array in C.


#include <stdio.h>
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Reverse the array


for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
printf("Reversed array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
OUTPUT:
Enter the size of the array: 5
Enter 5 elements: 1 2 3 4 5
Reversed array: 5 4 3 2 1

17. Remove the duplicates in the array in C


#include <stdio.h>
int main() {
int n, i, j, k;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];

printf("Enter %d elements: ", n);


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

// Remove duplicates
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; ) {
if (arr[i] == arr[j]) {
// Shift elements left
for (k = j; k < n - 1; k++) {
arr[k] = arr[k + 1];
}
n--; // Reduce array size
} else {
j++;
}
}
}

// Print array after removing duplicates


printf("Array after removing duplicates: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
OUTPUT:
Enter the size of the array: 7
Enter 7 elements: 1 2 2 3 4 4 5
Array after removing duplicates: 1 2 3 4 5

18. Program to implement matrix multiplication in C.


#include <stdio.h>
int main() {
int r1, c1, r2, c2;
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);

// Check if multiplication is possible


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

int mat1[r1][c1], mat2[r2][c2], result[r1][c2];


// Input first matrix
printf("Enter elements of first matrix:\n");
for (int i = 0; i < r1; i++)
for (int j = 0; j < c1; j++)
scanf("%d", &mat1[i][j]);

// Input second matrix


printf("Enter elements of second matrix:\n");
for (int i = 0; i < r2; i++)
for (int j = 0; j < c2; j++)
scanf("%d", &mat2[i][j]);

// Matrix multiplication
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
result[i][j] = 0; // Initialize result matrix to 0
for (int k = 0; k < c1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}

// Print result
printf("Resultant matrix:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}

OUTPUT:
Enter rows and columns of first matrix: 2 3
Enter rows and columns of second matrix: 3 2
Enter elements of first matrix:
123
456
Enter elements of second matrix:
78
9 10
11 12
Resultant matrix:
58 64
139 154
19. Implement Bubble sort in C.
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Bubble Sort algorithm


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

// Print sorted array


printf("Sorted array in ascending order: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
OUTPUT:
Enter the number of elements: 5
Enter 5 elements: 5 2 9 1 3
Sorted array in ascending order: 1 2 3 5 9

20. Implement Selection sort in C.


#include <stdio.h>
int main() {
int n, i, j, min_index, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Selection Sort algorithm
for (i = 0; i < n - 1; i++) {
min_index = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j; // Find the minimum element in unsorted array
}
}
// Swap the found minimum element with the first element
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}

// Print sorted array


printf("Sorted array in ascending order: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
OUTPUT:
Enter the number of elements: 5
Enter 5 elements: 64 25 12 22 11
Sorted array in ascending order: 11 12 22 25 64

21. Implement Linear search in C.


#include <stdio.h>
int main() {
int n, i, key, found = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the element to search: ");
scanf("%d", &key);

// Linear Search
for (i = 0; i < n; i++) {
if (arr[i] == key) {
found = 1;
break;
}
}
if (found)
printf("Element %d found at position %d.\n", key, i + 1);
else
printf("Element %d not found in the array.\n", key);

return 0;
}
OUTPUT:
Enter the number of elements: 5
Enter 5 elements: 10 20 30 40 50
Enter the element to search: 30
Element 30 found at position 3.

22. Implement Binary search in C.


#include <stdio.h>
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;

while (low <= high) {


int mid = low + (high - low) / 2; // avoid overflow

if (arr[mid] == key)
return mid; // element found
else if (arr[mid] < key)
low = mid + 1; // search in the right half
else
high = mid - 1; // search in the left half
}
return -1; // element not found
}

int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91};
int n = sizeof(arr) / sizeof(arr[0]);
int key;
printf("Enter the element to search: ");
scanf("%d", &key);
int result = binarySearch(arr, n, key);
if (result != -1)
printf("Element %d found at index %d\n", key, result);
else
printf("Element %d not found in the array\n", key);
return 0;
}

OUTPUT:
Enter the element to search: 23
Element 23 found at index 5
23. Implement Linear search in C using recursion.
#include <stdio.h>

// Recursive function for linear search


int linearSearch(int arr[], int n, int key, int index) {
if (index >= n) {
return -1; // element not found
}
if (arr[index] == key) {
return index; // element found
}
return linearSearch(arr, n, key, index + 1); // check next element
}

int main() {
int arr[] = {3, 7, 1, 9, 12, 5, 8};
int n = sizeof(arr) / sizeof(arr[0]);
int key;
printf("Enter the element to search: ");
scanf("%d", &key);
int result = linearSearch(arr, n, key, 0);
if (result != -1)
printf("Element %d found at index %d\n", key, result);
else
printf("Element %d not found in the array\n", key);
return 0;
}
OUTPUT:
Enter the element to search: 12
Element 12 found at index 4

24. Implement Binary search in C using recursion.


#include <stdio.h>

// Recursive function for binary search


int binarySearchRecursive(int arr[], int low, int high, int key) {
if (low > high) {
return -1; // element not found
}
int mid = low + (high - low) / 2;

if (arr[mid] == key)
return mid; // element found
else if (arr[mid] < key)
return binarySearchRecursive(arr, mid + 1, high, key); // search right half
else
return binarySearchRecursive(arr, low, mid - 1, key); // search left half
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91};
int n = sizeof(arr) / sizeof(arr[0]);
int key;
printf("Enter the element to search: ");
scanf("%d", &key);
int result = binarySearchRecursive(arr, 0, n - 1, key);
if (result != -1)
printf("Element %d found at index %d\n", key, result);
else
printf("Element %d not found in the array\n", key);

return 0;
}
OUTPUT:
Enter the element to search: 23
Element 23 found at index 5

25. Program to swap two numbers using pointers.


#include <stdio.h>
// Function to swap two numbers using pointers
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x, y;
printf("Enter two numbers: ");
scanf("%d%d ", &x, &y);
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(&x, &y); // passing addresses of x and y
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
OUTPUT:
Enter first number: -5
Enter second number: 15
Before swapping: x = -5, y = 15
After swapping: x = 15, y = -5

26. Program to implement matrix addition using pointers.


#include <stdio.h>
int main() {
int rows, cols;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);
int matrix1[rows][cols], matrix2[rows][cols], sum[rows][cols];

// Input first matrix


printf("Enter elements of first matrix:\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
scanf("%d", (*(matrix1 + i) + j));
}
}
// Input second matrix
printf("Enter elements of second matrix:\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
scanf("%d", (*(matrix2 + i) + j));
}
}

// Matrix addition
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
*(*(sum + i) + j) = *(*(matrix1 + i) + j) + *(*(matrix2 + i) + j);
}
}

// Print the sum matrix


printf("Sum of the two matrices:\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
printf("%d\t", *(*(sum + i) + j));
}
printf("\n");
}
return 0;
}
OUTPUT:
Enter number of rows: 2
Enter number of columns: 2
Enter elements of first matrix:
12
34
Enter elements of second matrix:
56
78
Sum of the two matrices:
6 8
10 12
27. Program to illustrate usage of malloc(), realloc() and free() functions.
#include <stdio.h>
#include <stdlib.h>

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

// Allocate memory using malloc()


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

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

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

// Resize memory using realloc()


printf("Enter new size of array: ");
scanf("%d", &newSize);

arr = (int*)realloc(arr, newSize * sizeof(int));


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

// If new size is greater, input additional elements


if (newSize > n) {
printf("Enter %d new elements:\n", newSize - n);
for (int i = n; i < newSize; i++) {
scanf("%d", &arr[i]);
}
}
// Display elements after realloc
printf("Array elements after realloc:\n");
for (int i = 0; i < newSize; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Free allocated memory


free(arr);
printf("Memory freed successfully.\n");
return 0;
}
OUTPUT:
Enter the number of elements: 3
Enter 3 elements:
123
Original array elements:
123
Enter new size of array: 5
Enter 2 new elements:
45
Array elements after realloc:
12345
Memory freed successfully.

28. Implement string handling functions using string library.


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

int main() {
char str1[100], str2[100];
char str3[100];

// Input two strings


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

printf("Enter second string: ");


fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = '\0'; // Remove newline

// strlen() - length of string


printf("\nLength of first string: %lu\n", strlen(str1));
printf("Length of second string: %lu\n", strlen(str2));

// strcpy() - copy string


strcpy(str3, str1);
printf("\nAfter copying, str3: %s\n", str3);
// strcat() - concatenate strings
strcat(str1, str2);
printf("\nAfter concatenation, str1: %s\n", str1);

// strcmp() - compare strings


int cmp = strcmp(str2, str3);
if (cmp == 0)
printf("\nstr2 and str3 are equal.\n");
else if (cmp < 0)
printf("\nstr2 is less than str3.\n");
else
printf("\nstr2 is greater than str3.\n");

return 0;
}
OUTPUT:
Enter first string: Hello
Enter second string: World
Length of first string: 5
Length of second string: 5

After copying, str3: Hello

After concatenation, str1: HelloWorld

str2 is greater than str3.

29. Implement string reverse without using string functions.


#include <stdio.h>
int main() {
char str[100], reversed[100];
int i = 0, j, length = 0;
// Input string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Remove newline character if present


if (str[0] != '\0' && str[0] != '\n') {
while (str[length] != '\0' && str[length] != '\n') {
length++;
}
}

// Reverse the string


j = 0;
for (i = length - 1; i >= 0; i--) {
reversed[j++] = str[i];
}
reversed[j] = '\0'; // Null-terminate the reversed string

// Display reversed string


printf("Reversed string: %s\n", reversed);
return 0;
}
OUTPUT:
Enter a string: Hello
Reversed string: olleH

30. Implement string to lowercase and vice versa with using string functions.
#include <stdio.h>
int main() {
char str[100];
int i;

// Input string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Remove newline character if present


if (str[0] != '\0' && str[0] != '\n') {
for(i = 0; str[i] != '\0'; i++) {
if(str[i] == '\n') {
str[i] = '\0';
break;
}
}
}

// Convert to lowercase
char lower[100];
for(i = 0; str[i] != '\0'; i++) {
if(str[i] >= 'A' && str[i] <= 'Z') {
lower[i] = str[i] + 32; // ASCII difference between uppercase and lowercase
} else {
lower[i] = str[i];
}
}
lower[i] = '\0';

// Convert to uppercase
char upper[100];
for(i = 0; str[i] != '\0'; i++) {
if(str[i] >= 'a' && str[i] <= 'z') {
upper[i] = str[i] - 32; // ASCII difference
} else {
upper[i] = str[i];
}
}
upper[i] = '\0';

// Display results
printf("Original string: %s\n", str);
printf("Lowercase: %s\n", lower);
printf("Uppercase: %s\n", upper);
return 0;
}
OUTPUT:
Enter a string: Hello World
Original string: Hello World
Lowercase: hello world
Uppercase: HELLO WORLD

31. Program to implement Student information using structures.


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

// Define a structure for Student


struct Student {
int id;
char name[50];
int age;
float marks;
};

int main() {
struct Student s1;
// Input student information
printf("Enter Student ID: ");
scanf("%d", &[Link]);
// Clear newline left in input buffer
getchar();
printf("Enter Student Name: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0'; // remove newline

printf("Enter Student Age: ");


scanf("%d", &[Link]);
printf("Enter Student Marks: ");
scanf("%f", &[Link]);

// Display student information


printf("\n--- Student Information ---\n");
printf("ID: %d\n", [Link]);
printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);
printf("Marks: %.2f\n", [Link]);
return 0;
}
OUTPUT:
Enter Student ID: 101
Enter Student Name: Alice
Enter Student Age: 20
Enter Student Marks: 88.5

--- Student Information ---


ID: 101
Name: Alice
Age: 20
Marks: 88.50

32. Program to implement self-referential structure in C.


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

// Define a self-referential structure


struct Node {
int data;
struct Node *next; // pointer to the same type of structure
};

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

// Allocate memory for nodes


head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));

// Assign data and link nodes


head->data = 10;
head->next = second;

second->data = 20;
second->next = third;

third->data = 30;
third->next = NULL;

// Print linked list


struct Node *ptr = head;
printf("Linked list elements: ");
while (ptr != NULL) {
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("\n");

// Free memory
free(head);
free(second);
free(third);

return 0;
}
OUTPUT:
Linked list elements: 10 20 30

33. Implement union and typedef in a program in C.


#include <stdio.h>
// Using typedef to define a union type
typedef union {
int intVal;
float floatVal;
char charVal;
} Data;

int main() {
Data d;
// Using the union
printf("Enter an integer value: ");
scanf("%d", &[Link]);
printf("You entered integer: %d\n", [Link]);

printf("Enter a float value: ");


scanf("%f", &[Link]);
printf("You entered float: %.2f\n", [Link]);
printf("Enter a character value: ");
scanf(" %c", &[Link]); // space before %c to skip newline
printf("You entered character: %c\n", [Link]);

// Note: Only the last assigned value is valid because union shares memory
printf("\nCurrently stored value in union is character: %c\n", [Link]);
return 0;
}
OUTPUT:
Enter an integer value: 10
You entered integer: 10
Enter a float value: 3.14
You entered float: 3.14
Enter a character value: A
You entered character: A

Currently stored value in union is character: A


34. Find the number of characters, words, and lines of a given text file.
#include <stdio.h>
int main() {
FILE *file;
char filename[100], ch;
int characters = 0, words = 0, lines = 0;
int inWord = 0;
printf("Enter the filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if (file == NULL) {
printf("Could not open file %s\n", filename);
return 1;
}

while ((ch = fgetc(file)) != EOF) {


characters++;
// Count lines
if (ch == '\n') {
lines++;
}

// Count words manually (space, tab, newline as separators)


if (ch == ' ' || ch == '\t' || ch == '\n') {
inWord = 0;
} else if (inWord == 0) {
inWord = 1;
words++;
}
}
fclose(file);
printf("Number of characters: %d\n", characters);
printf("Number of words: %d\n", words);
printf("Number of lines: %d\n", lines);
return 0;
}
OUTPUT:
Enter the filename: [Link]
Number of characters: 32
Number of words: 6
Number of lines: 2

[Assume [Link] contains:

Hello world
This is C programming.]
35. Program to merge two files into a third file.
#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *file1, *file2, *file3;
char filename1[100], filename2[100], filename3[100];
char ch;
// Input file names
printf("Enter the name of first file: ");
scanf("%s", filename1);
printf("Enter the name of second file: ");
scanf("%s", filename2);
printf("Enter the name of third file (merged file): ");
scanf("%s", filename3);

// Open first file in read mode


file1 = fopen(filename1, "r");
if (file1 == NULL) {
printf("Could not open file %s\n", filename1);
return 1;
}

// Open second file in read mode


file2 = fopen(filename2, "r");
if (file2 == NULL) {
printf("Could not open file %s\n", filename2);
fclose(file1);
return 1;
}

// Open third file in write mode


file3 = fopen(filename3, "w");
if (file3 == NULL) {
printf("Could not create file %s\n", filename3);
fclose(file1);
fclose(file2);
return 1;
}

// Copy contents of first file to third file


while ((ch = fgetc(file1)) != EOF) {
fputc(ch, file3);
}

// Copy contents of second file to third file


while ((ch = fgetc(file2)) != EOF) {
fputc(ch, file3);
}
printf("Files merged successfully into %s\n", filename3);

// Close all files


fclose(file1);
fclose(file2);
fclose(file3);
return 0;
}
OUTPUT:
Enter the name of first file: [Link]
Enter the name of second file: [Link]
Enter the name of third file (merged file): [Link]
Files merged successfully into [Link]

[Sample Input Files:

[Link]

Hello
This is file 1.

[Link]

Welcome
This is file 2.

Contents of [Link] after merging:

Hello
This is file 1.
Welcome
This is file 2.
]

36. Use file handling to print student memo.


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

struct Student {
int id;
char name[50];
float marks;
};

int main() {
FILE *file;
struct Student s;
// Open file in write mode to store student data
file = fopen("student_memo.txt", "w");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}

// Input student details


printf("Enter Student ID: ");
scanf("%d", &[Link]);
// Clear input buffer
getchar();
printf("Enter Student Name: ");
fgets([Link], sizeof([Link]), stdin);
printf("Enter Student Marks: ");
scanf("%f", &[Link]);

// Write student data to file


fprintf(file, "Student Memo\n");
fprintf(file, "----------------------\n");
fprintf(file, "ID: %d\n", [Link]);
fprintf(file, "Name: %s", [Link]); // fgets already includes newline
fprintf(file, "Marks: %.2f\n", [Link]);
fclose(file);

// Open file in read mode to print memo


file = fopen("student_memo.txt", "r");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}

printf("\n--- Student Memo ---\n");


char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);

return 0;
}
OUTPUT:
Enter Student ID: 101
Enter Student Name: Alice Johnson
Enter Student Marks: 88.5
--- Student Memo ---
Student Memo
----------------------
ID: 101
Name: Alice Johnson
Marks: 88.50

You might also like