[go: up one dir, main page]

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

Problem Solving

The document contains multiple C programming problems, each requiring the development of a specific program. Problems include checking for upper triangular matrices, matrix subtraction, name searching, binary matrix XOR, vowel replacement in strings, string comparison, character counting, and dynamic memory allocation. Each problem is accompanied by code snippets demonstrating the required functionality.

Uploaded by

anshunegi1236
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)
3 views39 pages

Problem Solving

The document contains multiple C programming problems, each requiring the development of a specific program. Problems include checking for upper triangular matrices, matrix subtraction, name searching, binary matrix XOR, vowel replacement in strings, string comparison, character counting, and dynamic memory allocation. Each problem is accompanied by code snippets demonstrating the required functionality.

Uploaded by

anshunegi1236
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/ 39

Problem 1 : Develop a C program to test whether a given matrix of order M × N is an upper

triangular matrix or not. An upper triangular matrix is the one in which all the elements
below its principal diagonal are zero.

#include<stdio.h>
int main() {
int M, N, i, j;
int isUpper = 1;

printf("Enter number of rows (M): "); scanf("%d", &M);


printf("Enter number of columns (N): ");
scanf("%d", &N);
int matrix[M][N];
printf("Enter elements of the matrix:\n");
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) { printf("Element [%d][%d]: ", i, j);

scanf("%d", &matrix[i][j]);
}
}
for (i = 1; i < M; i++) {
for (j = 0; j < i && j < N; j++) { if (matrix[i][j] != 0) {
isUpper = 0; break;
}
}
if (!isUpper)
break;
}

if (isUpper)
printf("The matrix is an upper triangular matrix.\n");
else
printf("The matrix is NOT an upper triangular matrix.\n");
return 0;
}
Problem 2 : Write a C program to read two square matrices of non-zero elements of order M
X M and then subtract the elements of the second matrix from the first matrix. Then display
the resultant matrix to the console.

#include <stdio.h>
int main() {
int m;

printf("Enter the order (m) of the square matrices: "); scanf("%d", &m);
if (m <= 0) {

printf("Order must be a positive integer.\n"); return 1;


}

int matrix1[m][m], matrix2[m][m], result[m][m];

printf("Enter elements of the first matrix (%d x %d):\n", m, m);

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

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

printf("matrix1[%d][%d]: ", i, j);

scanf("%d", &matrix1[i][j]);

}
}

printf("Enter elements of the second matrix (%d x %d):\n", m, m);


for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
printf("matrix2[%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
printf("\nResultant Matrix (Matrix1 - Matrix2):\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}
return 0;
}
Problem 3 : Develop a C program to accept the names in a 2-D array and then search a name
entered by the user. Display an appropriate message to the output screen if found.

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

#define MAX_NAMES 100


#define MAX_LENGTH 50

int main() {
char names[MAX_NAMES][MAX_LENGTH], search[MAX_LENGTH];
int n, found = 0;

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


scanf("%d", &n);
getchar();

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


printf("Enter name %d: ", i + 1);
fgets(names[i], MAX_LENGTH, stdin);
names[i][strcspn(names[i], "\n")] = '\0';
}

printf("Enter the name to search: ");


fgets(search, MAX_LENGTH, stdin);
search[strcspn(search, "\n")] = '\0';

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


if (strcmp(names[i], search) == 0) {
printf("'%s' found at position %d.\n", search, i + 1);
found = 1;
break;
}
}
if (!found) {
printf("'%s' not found in the list.\n", search);
}

return 0;
}
Problem 4 : Develop a C program to read two square binary matrices of order N x N from
the user and perform the XOR on the elements of the matrices and print the resultant matrix
to the output screen.

#include <stdio.h>
#define MAX 100
int main() {
int matrix1[MAX][MAX], matrix2[MAX][MAX], result[MAX][MAX];
int N;
printf("Enter the order of the square matrices (N x N): ");
scanf("%d", &N);
if (N <= 0 || N > MAX) {
printf("Invalid matrix size. Please use 1 to %d.\n", MAX); return 1;}
printf("Enter elements of first %d x %d binary matrix (0 or 1):\n", N, N); for (int i = 0; i < N;
i++) {
for (int j = 0; j < N; j++) { scanf("%d", &matrix1[i][j]);
if (matrix1[i][j] != 0 && matrix1[i][j] != 1) {
printf("Invalid input. Only binary values (0 or 1) are allowed.\n");

return 1;
}
}}
printf("Enter elements of second %d x %d binary matrix (0 or 1):\n", N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
scanf("%d", &matrix2[i][j]);
if (matrix2[i][j] != 0 && matrix2[i][j] != 1) {
printf("Invalid input. Only binary values (0 or 1) are allowed.\n"); return 1;
}
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
result[i][j] = matrix1[i][j] ^ matrix2[i][j];
}
}
printf("Resultant matrix after XOR operation:\n"); for (int i = 0; i < N; i++) {

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


printf("%d ", result[i][j]); }
printf("\n");
}
return 0;
}
Problem 5 : Write a C program to read a sentence from the user and replace all the
occurrences of vowels with a X character. Display the modified string to the console.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char sentence[1000]; printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin); for (int i = 0; sentence[i] != '\0'; i++) {
char ch = tolower(sentence[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
sentence[i] = 'X';
}
}
printf("Modified sentence: %s\n", sentence);
return 0;
}
Problem 7 : Develop a C program to compare two strings using a UDF and return 1 if the
strings are equal and 0 otherwise without using the built-in function strcmp(). Display an
appropriate message to the output screen.
Sample Input:
Enter two strings Welcome welcome
Output:
The Strings are not equal.

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

void removeNewline(char str[]) {


size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
}
}

int compareStrings(char str1[], char str2[]) {


removeNewline(str1);
removeNewline(str2);

int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
return 0;
}
i++;
}
return (str1[i] == '\0' && str2[i] == '\0');
}

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

printf("Enter the first string: ");


fgets(str1, sizeof(str1), stdin);
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);

if (compareStrings(str1, str2)) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Problem 8 : Develop a C program to find the number of occurrences of each alphabet in a
string accepted from the user and display the same to the output screen. Assume that the
string contains only alphabets.

#include <stdio.h>
#include <ctype.h> // for tolower()

int main() {
char str[1000];
int count[26] = {0};

printf("Enter a string (alphabets only): ");


fgets(str, sizeof(str), stdin); // safer alternative to gets()

for (int i = 0; str[i] != '\0'; i++) {


char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
count[ch - 'a']++;
}
}

printf("\nOccurrences of each alphabet:\n");


for (int i = 0; i < 26; i++) {
if (count[i] > 0) {
printf("%c: %d\n", i + 'a', count[i]);
}
}

return 0;
}
problem 9 : Design a UDF in C to find the product and quotient of two numbers passed to it
from the calling program. Display the product and the quotient in the main program. Read the
two numbers in the main program & also display their product and quotient. Implement using
a pointer.

#include <stdio.h>
void calculateProductAndQuotient(float a, float b, float *product, float *quotient);

int main() {
float num1, num2; float product, quotient;
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
if (num2 == 0) {
printf("Error: Division by zero is not allowed.\n");
return 1;
}
calculateProductAndQuotient(num1, num2, &product, &quotient);
printf("Product: %.2f\n", product);
printf("Quotient: %.2f\n", quotient);

return 0;
}
void calculateProductAndQuotient(float a, float b, float *product, float *quotient) {
*product = a * b;
*quotient = a/b;
}
Problem 10 : Write a C program to accept N integers from the user into an array. If any
integer is positive then subtract 2 from it, if integer is negative add 1 to it and if zero then do
nothing. Implement a UDF using a pointer to perform these operations and finally display the
modified array to the screen in the calling program.

Sample Input:
1 3 -5 0 8 -4 -1
Output:
-1 1 -4 0 6 -3 0

#include <stdio.h>

void modifyArray(int *arr, int n) {


for (int i = 0; i < n; i++) {
if (*(arr + i) > 0) {
*(arr + i) -= 2;
} else if (*(arr + i) < 0) {
*(arr + i) += 1;
}}}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d integers:\n", n);

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


scanf("%d", &arr[i]);
}
modifyArray(arr, n);
printf("Modified array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Problem 11 : Design a UDF using pointer that returns 1 if the string is a palindrome
otherwise zero. Accept a string from user in the calling program. Display an appropriate
message in the calling program. Implement a C program for the same. Ignore the case.

Sample Input/Output:
Input:
Enter a String: Rotator
Output:
Rotator is a palindrome

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

int isPalindrome(char *str) {


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

while (start < end) {


if (tolower(*start) != tolower(*end)) {
return 0;
}
start++;
end--;
}
return 1;
}

int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';

if (isPalindrome(str)) {
printf("The string \"%s\" is a palindrome.\n", str);
} else {
printf("The string \"%s\" is not a palindrome.\n", str);
}

return 0;
}
Problem 12 : Design a UDF that returns the count of special characters present in a sentence
passed to it using pointer to the calling program. Implement a C program to read a string in
the main program and display all the count of the special characters returned by the function
to the console.
Sample Input:
Enter a String: Rotation%# is$? ?rotating $motion?
Output:
Special Character Count: 10

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

void countSpecialCharacters(const char *str, int *count) {


*count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (!isalnum(str[i]) && !isspace(str[i])) {
(*count)++;
}
}
}

int main() {
char sentence[1000];
int specialCharCount;

printf("Enter a sentence: ");


if (fgets(sentence, sizeof(sentence), stdin)) {

size_t len = strlen(sentence);


if (len > 0 && sentence[len - 1] == '\n') {
sentence[len - 1] = '\0';
}
countSpecialCharacters(sentence, &specialCharCount);
printf("The number of special characters in the sentence is: %d\n",
specialCharCount);
} else {
printf("Error reading input.\n");
}

return 0;
}
Problem 13 : Write a C program to dynamically allocate memory for an integer array of size
N, allow the user to input N integers, resize the array to N+M using realloc to add M more
integers, compute the sum of all N+M integers, and properly release the allocated memory.

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

int main() {
int *arr;
int N, M, sum = 0;

printf("Enter the initial size of the array (N): ");


scanf("%d", &N);

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


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

printf("Enter %d integers:\n", N);


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

printf("Enter the number of additional elements to add (M): ");


scanf("%d", &M);

int newSize = N + M;
int *temp = realloc(arr, newSize * sizeof(int));
if (temp == NULL) {
printf("Memory reallocation failed.\n");
free(arr);
return 1;
}
arr = temp;
printf("Enter %d more integers:\n", M);
for (int i = N; i < newSize; i++) {
scanf("%d", &arr[i]);
}

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


sum += arr[i];
}

printf("The sum of all %d integers is: %d\n", newSize, sum);

free(arr);
return 0;
}
Problem 14 : Write a C program to dynamically allocate memory for two user-input strings,
concatenate them into a new dynamically allocated string, print the result and free all
allocated memory.

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

int main() {
char *str1, *str2, *result;
int len1, len2;

printf("Enter the length of the first string: ");


if (scanf("%d", &len1) != 1 || len1 <= 0) {
printf("Invalid length.\n");
return 1;
}
getchar();
str1 = (char *)malloc((len1 + 1) * sizeof(char));
if (str1 == NULL) {
printf("Memory allocation failed for str1.\n");
return 1;
}
printf("Enter the first string: ");
if (fgets(str1, len1 + 1, stdin) == NULL) {
printf("Error reading the first string.\n");
free(str1);
return 1;
}
str1[strcspn(str1, "\n")] = '\0';

printf("Enter the length of the second string: ");


if (scanf("%d", &len2) != 1 || len2 <= 0) {
printf("Invalid length.\n");
free(str1);
return 1;
}
getchar();
str2 = (char *)malloc((len2 + 1) * sizeof(char));
if (str2 == NULL) {
printf("Memory allocation failed for str2.\n");
free(str1);
return 1;
}
printf("Enter the second string: ");
if (fgets(str2, len2 + 1, stdin) == NULL) {
printf("Error reading the second string.\n");
free(str1);
free(str2);
return 1;
}
str2[strcspn(str2, "\n")] = '\0';

result = (char *)malloc(len1 + len2 + 1);


if (result == NULL) {
printf("Memory allocation failed for result.\n");
free(str1);
free(str2);
return 1;
}

strcpy(result, str1);
strcat(result, str2);

printf("Concatenated string: %s\n", result);


free(str1);
free(str2);
free(result);
return 0;
}
Problem 15 : Develop a program in C to read a structure in the main program of an
Employee that contains Name, EmpCode and Salary as the members. Write a function to
display the details of the employee in the following format.

#include <stdio.h>
#include <string.h>
struct Employee {
char name[50];
int empCode;
float salary;
};

void displayEmployee(struct Employee emp) {


printf("\nEmployee Details:\n");
printf("Name : %s\n", emp.name);
printf("Emp Code : %d\n", emp.empCode);
printf("Salary : %.2f\n", emp.salary);
}

int main() {
struct Employee emp;
printf("Enter employee name: ");
fgets(emp.name, sizeof(emp.name), stdin);
emp.name[strcspn(emp.name, "\n")] = '\0';
printf("Enter employee code: ");
scanf("%d", &emp.empCode);
printf("Enter employee salary: ");
scanf("%f", &emp.salary);
displayEmployee(emp);
return 0;
}
Problem 16 : Develop a C program to read the attributes of an item from the user such as
ItemCode, ItemName, Quantity and Rate. Implement a C program using a structure to find
the total cost of the inventory of storing N items in the stock.

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

struct Item {
int itemCode;
char itemName[50];
int quantity;
float rate;
};

int main() {
int n, i;
float totalCost = 0;

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


if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid input.\n");
return 1;
}

struct Item items[n];

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


printf("\nEnter details for item %d:\n", i + 1);

printf("Item Code: ");


if (scanf("%d", &items[i].itemCode) != 1) {
printf("Invalid input.\n");
return 1;
}

printf("Item Name: ");


getchar();
if (fgets(items[i].itemName, sizeof(items[i].itemName), stdin) == NULL) {
printf("Error reading item name.\n");
return 1;
}
items[i].itemName[strcspn(items[i].itemName, "\n")] = '\0';

printf("Quantity: ");
if (scanf("%d", &items[i].quantity) != 1 || items[i].quantity < 0) {
printf("Invalid input.\n");
return 1;
}

printf("Rate: ");
if (scanf("%f", &items[i].rate) != 1 || items[i].rate < 0) {
printf("Invalid input.\n");
return 1;
}
}

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


totalCost += items[i].quantity * items[i].rate;
}

printf("\nTotal inventory cost: %.2f\n", totalCost);


return 0;
}
Problem 17 : Develop a C program to display Name, Roll Number, Date of Birth and Date
of Admission details of a student read from the keyboard where the date of birth and date of
admission further consists of three members such as day, month and year in a separate
structure. Implement using a C structure.

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

struct Date {
int day;
int month;
int year;
};

struct Student {
char name[50];
int rollNumber;
struct Date dob;
struct Date doa;
};

int main() {
struct Student s;

// Input student details


printf("Enter student name: ");
if (fgets(s.name, sizeof(s.name), stdin) == NULL) {
fprintf(stderr, "Error reading student name.\n");
return 1;
}
s.name[strcspn(s.name, "\n")] = '\0';
printf("Enter roll number: ");
if (scanf("%d", &s.rollNumber) != 1) {
fprintf(stderr, "Invalid input for roll number.\n");
return 1;
}

printf("Enter Date of Birth (dd mm yyyy): ");


if (scanf("%d %d %d", &s.dob.day, &s.dob.month, &s.dob.year) != 3) {
fprintf(stderr, "Invalid input for date of birth.\n");
return 1;
}

printf("Enter Date of Admission (dd mm yyyy): ");


if (scanf("%d %d %d", &s.doa.day, &s.doa.month, &s.doa.year) != 3) {
fprintf(stderr, "Invalid input for date of admission.\n");
return 1;
}

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


printf("Name: %s\n", s.name);
printf("Roll Number: %d\n", s.rollNumber);
printf("Date of Birth: %02d-%02d-%04d\n", s.dob.day, s.dob.month, s.dob.year);
printf("Date of Admission: %02d-%02d-%04d\n", s.doa.day, s.doa.month, s.doa.year);

return 0;
}
Problem 18 : Develop a C program to read the following details of N employees into
appropriate data storage. EmpNo, Name and Salary. Display all the details of the employees
in the descending order of their salary to the console.
#include <stdio.h>
#include <string.h>

#define MAX_EMPLOYEES 100


#define NAME_LENGTH 50

struct Employee {
int empNo;
char name[NAME_LENGTH];
float salary;
};

void sortEmployeesBySalary(struct Employee emp[], int n) {


struct Employee temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (emp[j].salary < emp[j + 1].salary) {
temp = emp[j];
emp[j] = emp[j + 1];
emp[j + 1] = temp;
}
}
}
}

int main() {
struct Employee emp[MAX_EMPLOYEES];
int n;
printf("Enter the number of employees: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > MAX_EMPLOYEES) {
printf("Invalid number of employees.\n");
return 1;
}

getchar();

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


printf("\nEnter details of employee %d:\n", i + 1);

printf("Employee Number: ");


if (scanf("%d", &emp[i].empNo) != 1) {
printf("Invalid input for employee number.\n");
return 1;
}

getchar();

printf("Name: ");
if (fgets(emp[i].name, sizeof(emp[i].name), stdin) == NULL) {
printf("Error reading name.\n");
return 1;
}
emp[i].name[strcspn(emp[i].name, "\n")] = '\0';

printf("Salary: ");
if (scanf("%f", &emp[i].salary) != 1 || emp[i].salary < 0) {
printf("Invalid input for salary.\n");
return 1;
}

getchar();
}

sortEmployeesBySalary(emp, n);

printf("\nEmployee details in descending order of salary:\n");


printf("EmpNo\tName\t\tSalary\n");
for (int i = 0; i < n; i++) {
printf("%d\t%-15s\t%.2f\n", emp[i].empNo, emp[i].name, emp[i].salary);
}

return 0;
}
Problem 19 : Write a C program to count the number of words, characters, and lines in a text
file.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main() {
FILE *file;
char filename[100];
char 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) {
perror("Error opening file");
return 1;
}

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


characters++;

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

if (isspace(ch)) {
inWord = 0;
} else if (!inWord) {
inWord = 1;
words++;
}
}

fclose(file);

if (characters > 0 && ch != '\n') {


lines++;
}

printf("Characters: %d\n", characters);


printf("Words: %d\n", words);
printf("Lines: %d\n", lines);

return 0;
}

Problem 20 : Design a C program to add to an existing file present in the current drive by
reading the contents from another file. Read the names of both the files from the user.
Display the new file to the console by converting all the alphabets to lowercase.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char sourceFileName[100], targetFileName[100];
FILE *sourceFile, *targetFile;
char ch;

printf("Enter the source file name: ");


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

sourceFile = fopen(sourceFileName, "r");


if (sourceFile == NULL) {
perror("Error opening source file");
return 1;
}

targetFile = fopen(targetFileName, "a");


if (targetFile == NULL) {
perror("Error opening target file");
fclose(sourceFile);
return 1;
}

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


fputc(ch, targetFile);
}

fclose(sourceFile);
fclose(targetFile);

targetFile = fopen(targetFileName, "r");


if (targetFile == NULL) {
perror("Error opening target file for reading");
return 1;
}

printf("\nContents of '%s' after appending (in lowercase):\n", targetFileName);


while ((ch = fgetc(targetFile)) != EOF) {
putchar(tolower(ch));
}

fclose(targetFile);
return 0;
}

You might also like