Search code examples
cstringloopscharacter-arrays

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


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);

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++;
            }   
        }   
    }