128k views
4 votes
Devise a C program that determines whether a 1D array of char (string) is a sparse array or not. The 1D array has dimensions 15 elements. We define an array to be sparse if its number of letters (lower case or capitals) is at least twice as large as the number of the rest of the characters in the string. The program reads the strings from an input file. The results re displayed on the screen. C code only.

User Kathia
by
7.3k points

1 Answer

4 votes

Final answer:

A C program is provided to determine if a 1D char array is a sparse array by reading strings from an input file and comparing the count of letters to other characters. The output indicates whether each string is sparse or not.

Step-by-step explanation:

A sparse array is defined as an array where the number of letters (either lowercase or uppercase) is at least twice the number of other characters. To determine if a 1D char array with 15 elements meets this criterion, we can write a C program that reads strings from an input file and counts the occurrences of letters versus other characters. When the program finishes processing, it displays the results, indicating whether each string is sparse or not.

Here is an example of how such a program might look:

#include
#include

#define SIZE 15

int main() {
FILE *fileptr;
char str[SIZE + 1]; /* Extra character for the null-terminator */
int letter_count, other_count;

/* Open input file in read mode */
fileptr = fopen("input.txt", "r");
if (fileptr == NULL) {
perror("Error opening file");
return 1;
}

/* Read strings from the file */
while (fgets(str, SIZE + 1, fileptr)) {
letter_count = other_count = 0;

/* Count letters and other characters */
for (int i = 0; str[i] != '\0' && i < SIZE; i++) {
if (isalpha(str[i])) {
letter_count++;
} else if (str[i] != '\\') {
/* Ignore newlines when counting other characters */
other_count++;
}
}

/* Check if the array is sparse and display the result */
if (letter_count >= 2 * other_count) {
printf("%s - Sparse\\", str);
} else {
printf("%s - Not sparse\\", str);
}
}

fclose(fileptr);
return 0;
}

This code snippet opens an input file, reads each string, and counts the letters and other characters, determining if the array is a sparse array. The result is then printed to the screen.