I am trying to increments the chars in my string (ie string x = (aaaa) all the way through (zzzz)). Is there a specific way I can use a loop to do this? I'm sorry if my question is newbie, I'm new to coding...XP
2 Answers
One way would be to interpret characters 'a' to 'z' as digits in a number with base 26, start at "aaaa" (representing 0), and then adding 1 to the last string. Add or subtract 'a' for conversion between character and "digit" value.
Instead of storing the string as your state, you could also store the values, and convert to the string for passing to crypt only.
On addition, use a carry variable, and break the loop when you find you're out of characters and still have a carry value (which means you're back to "aaaa").
Another way would be four nested loops (which is very inflexible), or recursion, with any level of recursion controlling one character.
-
Thank you for replying! Could you describe how I would set up the four nested loops? That is, unless you think that the 26-base system would be easier, but as far as I have researched, it seems much more complicated than say, converting back and forth between a hexadecimal system. Thank you in advance.– Jason_VFeb 2, 2017 at 4:18
-
Nested loops would be like
char key[5]; key[4] = 0; for (key[0] = 'a'; key[0] <= 'z'; key[0]++) for (key[1] = 'a'; key[1] <= 'z'; key[1]++) for (key[2] = 'a'; key[2] <= 'z'; key[2]++) for (key[3] = 'a'; key[3] <= 'z'; key[3]++) { printf("Here's a key: %s\n", key); }
– BlauelfFeb 2, 2017 at 10:43 -
-
@AsherHe That's matching the problem specification, but try making your code more generic, so it's easier to adapt it to changed requirements. For example you could make the code use one integer constant for maximum password length, and one string constant (or character array) for the characters to use, so if either of them ever changed, there was one place to modify.– BlauelfMar 26, 2019 at 14:22
If you meant iterating through the characters in the string, then you can use a for loop to do that.