When I input The quick brown fox jumps over the lazy dog
, the following program prints not a pangram
. Yet, I expect s
to be 26 and printf("pangram")
to be executed. What am I doing wrong?
#include <ctype.h>
#include <stdio.h>
#include <string.h>
char findpan(char arr[]) {
int i, j, count = 0;
for (i = 0; i < strlen(arr); i++) {
if (isalpha(arr[i]))
count++;
}
for (i = 0; i < strlen(arr); i++) {
for (j = i + 1; j < strlen(arr); j++) {
if (arr[i] == arr[j])
count--;
}
}
return (count);
}
int main() {
int s;
char str[60];
fgets(str, 60, stdin);
s = findpan(str);
if (s == 26)
printf("pangram");
else
printf("not a pangram");
return 0;
}
Here a Simple solution, I made the guess that you probably just want to know if it is or it isn't a pangram and so i've changed your function to a boolean one:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool findpan(char arr[]) {
int i,j;
for (i = 'a'; i < 'z'; ++i) { // goes through the alphabet
for (j = strlen(arr); j > 0; j--) // goes through the arr[]
if (tolower(arr[j]) == i) // checks if the letter exists
break; // breaks the inner for-loop if letter found
if (j == 0) // if letter not found
return false;
}
return true;
}
int main() {
bool isPangram;
char str[60];
fgets(str, 60, stdin);
isPangram = findpan(str);
if (isPangram)
printf("pangram");
else
printf("not a pangram");
return 0;
}
'a' to 'z' represent the range of the lowercase letters in Decimal numbers, in the ASCII table:
for (i = 'a'; i < 'z'; ++i)
tolower
converts arr[j]
character to lowercase and then compares it to i:
if (tolower(arr[j]) == i)
stdbool.h
is introduced for the use of bool
aka boolean:
#include <stdbool.h>