How to implement a loop to read the array of names that checks for number of upper case letters etc?

StackOverflow https://stackoverflow.com/questions/16311022

Question

The program as is is telling me there are 0 upper case 0 lower case 0 spaces and 0 tabs but 61 other characters for an array with 2 names that are lowercase. The names have 10 letters combined. I think I need a loop to iterate over the array but I'm not sure if that's correct or how I would do this.

for (i=0; i<n_names; i++){
    printf("%d: [[%s]]\n", i, names[i]);}
for (i=0; i<20; i++){
    gets(names[i]);

    while (s[i] != 0)
    {
        if (s[i] >= 'a' && s[i] <= 'z') {
            lowercase++;
            i++;
        }         
        else if (s[i] >= 'A' && s[i] <= 'Z') {
            uppercase++;
            i++;
        }                
        else if (s[i] == '  ') {         /* Tab - write '\t' for clarity! */
            tab++;
            i++;
        }
        else if (*names[i] == ' ') {
            spaces++;
            i++;
        }
        else {
            other++;
            i++;
        }
    }
}

printf("Your string has %d lowercase letter(s) \n",lowercase);
printf("Your string has %d uppercase letter(s) \n",uppercase);
printf("Your string has %d tab(s) \n",tab);
printf("Your string has %d space(s) \n", spaces);
printf("Your string has %d other character(s) \n",other);
Was it helpful?

Solution

int i, n_idx;
for (n_idx = 0; n_idx < n_names; n_idx++) {
    const char *s = names[n_idx];
    for (i = 0; s[i] != 0; i++) {   
        if (s[i] >= 'a' && s[i] <= 'z') {
            lowercase++;
        }    
        else if (s[i] >= 'A' && s[i] <= 'Z') {
            uppercase++;
        }    
        else if (s[i] == '\t') {    
            tab++;
        }   
        else if (s[i] == ' ') {
            spaces++;
        }   
        else{
            other++;
        }   
    }   
}

OTHER TIPS

I dont think you pasted the entire code, I presume you "s" points to strings in names. Also initialize "i" to zero before your while loop.

Please use standard functions islower, isupper and for tab you need to compare with '\t'

Other useful functions in ctype.h for your scenario.

#include <ctype.h>

int isalnum(int c);
int isalpha(int c);
int isascii(int c);
int isblank(int c);
int iscntrl(int c);
int isdigit(int c);
int isgraph(int c);
int islower(int c);
int isprint(int c);
int ispunct(int c);
int isspace(int c);
int isupper(int c);
int isxdigit(int c);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top