Search code examples
arrayscloopswhile-loopnew-operator

Struggle with loops


so I am super new to coding and am just following this tutorial series, the first task here is to create a checker for a password which includes upper/lower case, numbers and symbols, I am stuck at the very beginning howerver...so here's a bit of code and my problems:

int main()
{    
     int pw[21];
     int pwVUpper = 0;
     int pwnum = 0;

     printf("Please choose a password.\n");
     printf("Make sure it includes at least one number, lower and upper case letter and one of the symbols: !, _, $, -, /.\n");    
     scanf(" %c", pw);

     while((pwnum<=21)){
        if(isupper(pw[pwnum])){
                printf("lol!");
                pwnum++;
        }
     }    
     return 0;
}

so this was just the beginning for checking for the upper letter, I wannt to have the loop go through each letter of the "pw" array, and only then print "lol!", if it checks for an upper letter, however, it only ever checks the first letter in the array and only prints "lol!"once, even if the array happens to be with 2 capitals at any point.

I tried to have the array letter number associated with the variable pwnum and as the loop goes on, the variable increases and so the next letter would get checked.

JUST A HEADS UP: from various searching, I have come to see that there are much better solutions to what I am trying to do, but a lot of the keywords presented I have not gone over yet and would like to complete this with only the limited knowledge, as suggested by the tutorial series, I seem to misunderstand loops or something and at this point am really starting to feel brain damaged, probably am huh!


Solution

  • Here's the issue

     while((pwnum<=21)){
        if(isupper(pw[pwnum])){
                printf("lol!");
                pwnum++;
        }
     }  
    

    Notice that there are two statements inside the curly braces controlled by the if statement. Namely, a call to printf() and an increment of pwnum. This means that you only increment pwnum when you print "lol" — when you've found an upper case letter.

    Restructure the code like this:

     while((pwnum<=21)){
        if(isupper(pw[pwnum])){
                printf("lol!");
        }
        pwnum++;
     }  
    

    Now the index pwnum is incremented whether or not you found an upper case letter. This means that the program will move on to look at the next letter.

    ETA It's been pointed out (thanks @ryyker) that the array index also has an off by one problem. You do not want to try reading the value of pw[21] because in an array of 21 elements, a valid index is from 0 to 20 inclusive. Therefore, you should modify your loop as follows:

     while((pwnum<21))...
    

    There are other issues with the code as well, but hopefully this gets you past the current problem.