简体   繁体   中英

I'm not sure why my nested while loop is stopping after the first iteration

I have to write a C program that asks the user to input a string and it returns how many times each letter of the alphabet occurs in the string (ie. a appears 3 times). for example, if the user inputs the following string:

Hello

it is supposed to return the following

a or A appears 0 times 
b or B appears 0 times 
c or C appears 0 times 
d or D appears 0 times
e or E appears 1 times
(it does this for the whole alphabet) 

Code:

#include<stdio.h>
#include<stdlib.h>
#define MAX 1000

int main(){

    char str[MAX];
    int count[26]={0};

    printf("Enter your string \n");
    fgets(str,sizeof(str),stdin);

    char str1[]="abcdefghijklmnopqrstuvwxyz";
    char str2[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    int i=0;
    int j=0;
    while(i<26){

        while(str[j]!='\0'){
            if(str[j]==str1[i]||str[j]==str2[i]){
                count[i]++;
            }
            j++;
        }

        printf("Letter %c or %c appears %d times\n",str1[i],str2[i],count[i]);
        i++;

    }
    return 0;
}

with what I have now it scans for a and then stops after that and just returns zero for every other letter

After the inner while loop

    while(str[j]!='\0'){
        if(str[j]==str1[i]||str[j]==str2[i]){
            count[i]++;
        }
        j++;
    }

j becomes equal to strlen( str ) and str[j] is equal to '\\0' So in the next iteration of the outer while loop the inner while loop has a condition equal to logical false. You need at least to reset the variable j to zero before the inner loop.

    j = 0;
    while(str[j]!='\0'){
        if(str[j]==str1[i]||str[j]==str2[i]){
            count[i]++;
        }
        j++;
    }

The reason of this logical error is that the variable j is not declared in the scope where it is used. Try to declare variables in minimal scopes where they are used.

Instead of the inner while loop it would be better to write a for loop like

for ( size_t j = 0; str[j] != '\0'; j++ )
{
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM