Practical No.
03
Practical Related Questions ANS
XIV 1) Ans
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void toLowercase(char* str) {
for (int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
}
// Function to perform linear search (case-insensitive)
int linearSearch(char* arr[], int size, char* target) {
toLowercase(target); // Convert target to lowercase
for (int i = 0; i < size; i++) {
char temp[100]; // Temporary array to store lowercase string
strcpy(temp, arr[i]);
toLowercase(temp); // Convert current string to lowercase
if (strcmp(temp, target) == 0) {
return i; // Return index if match found
}
}
return -1; // Return -1 if no match found
}
int main() {
char* strings[] = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
int size = sizeof(strings) / sizeof(strings[0]);
char target[100];
printf("Array of strings: ");
for (int i = 0; i < size; i++) {
printf("%s ", strings[i]);
}
printf("\n");
printf("Enter the string to search: ");
scanf("%s", target);
int result = linearSearch(strings, size, target);
if (result != -1) {
printf("String '%s' found at index %d\n", target, result);
} else {
printf("String '%s' not found in the array\n", target);
}
return 0;
}
Output:
2)Ans
#include <stdio.h>
#include <string.h>
// Function to perform linear search for substring
int linearSearch(char* arr[], int size, char* target) {
for (int i = 0; i < size; i++) {
if (strstr(arr[i], target) != NULL) {
return i; // Return index if substring found
}
}
return -1; // Return -1 if no substring found
}
int main() {
char* strings[] = {"Apple Pie", "Banana Split", "Cherry Cake", "Date Smoothie",
"Elderberry Jam"};
int size = sizeof(strings) / sizeof(strings[0]);
char target[100];
printf("Array of strings: ");
for (int i = 0; i < size; i++) {
printf("%s ", strings[i]);
}
printf("\n");
printf("Enter the substring to search: ");
scanf("%s", target);
int result = linearSearch(strings, size, target);
if (result != -1) {
printf("Substring '%s' found in '%s' at index %d\n", target, strings[result], result);
} else {
printf("Substring '%s' not found in the array\n", target);
}
return 0;
}
Output: