Start learning free

LESSON 195 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V2 in C#: A Length Rule and a Digit Flag

Practice Read the full explanation

Extend the length check with a second rule: the password must also contain at least one digit.

You start with:

string password = "Secret99";

Build:

Length: 8
Has digit: True
Strong

Rules:

  • Print "Length: " followed by the number of characters.
  • Loop through each character to set a boolean flag hasDigit, which starts as false and becomes true when a digit is seen.
  • Print "Has digit: " followed by the flag. Write it as True or False with a capital letter, exactly as in the example (your language's own boolean prints differently, so choose the text yourself).
  • If the length is at least 8 and hasDigit is true, print Strong; otherwise print Weak.

Try other passwords: with abcdefgh the output is

Length: 8
Has digit: False
Weak

char.IsDigit(c) tests a single char. Use (hasDigit ? "True" : "False") to print a capitalised True/False.

string password = "Secret99";

int length = password.Length;
Console.WriteLine("Length: " + length);
bool hasDigit = false;
foreach (char c in password) {
    if (char.IsDigit(c)) {
        hasDigit = true;
    }
}
Console.WriteLine("Has digit: " + (hasDigit ? "True" : "False"));
if (length >= 8 && hasDigit) {
    Console.WriteLine("Strong");
} else {
    Console.WriteLine("Weak");
}

STEP 1 OF 8
    Ctrl + Enter to check

    C# · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V2 in C#, explained

    Problem overview

    The password checker now has two rules. A password is Strong only if it has at least 8 characters and contains at least one digit. Otherwise it is Weak. The program prints three lines: the length, whether a digit was found, and the verdict.

    For "Secret99" the output is:

    Length: 8
    Has digit: True
    Strong
    

    The length is 8, the last two characters are digits, and both rules pass. For "abcdefgh" the length is still 8, but there is no digit, so the lines are Length: 8, Has digit: False and Weak.

    Approach: a flag set by a loop

    The length is easy: password.Length. Finding out whether the password contains a digit takes a loop, because the answer depends on every character.

    The standard tool here is a flag: a bool variable that starts at false, meaning "no digit seen yet". The loop looks at each character, and whenever it finds a digit it sets the flag to true. Nothing in the loop ever sets the flag back to false, so one digit anywhere is enough to leave it true at the end. If the loop finishes and the flag is still false, no character was a digit.

    After the loop, the two rules are combined with && (and): both must be true for Strong, and anything else is Weak.

    Step by step

    1. Store the length in an int named length and print the first line.
    2. Create the flag. hasDigit is a bool that starts at false.
    3. Loop over the characters. A foreach with a char variable c hands the loop one character of password per round.
    4. Test each character. Inside the loop, an if asks char.IsDigit(c). When it is true, the flag becomes true.
    5. Print the flag after the loop. The line goes outside the braces, so it runs once, when every character has been checked.
    6. Write the verdict. The condition length >= 8 && hasDigit selects Strong.
    7. Add the else. It catches every other case: too short, no digit, or both.

    The solution in C#

            string password = "Secret99";
    
            int length = password.Length;
            Console.WriteLine("Length: " + length);
            bool hasDigit = false;
            foreach (char c in password) {
                if (char.IsDigit(c)) {
                    hasDigit = true;
                }
            }
            Console.WriteLine("Has digit: " + (hasDigit ? "True" : "False"));
            if (length >= 8 && hasDigit) {
                Console.WriteLine("Strong");
            } else {
                Console.WriteLine("Weak");
            }
    

    The C# details worth a closer look:

    • foreach over a string. A string can be walked like a collection of char values. The loop variable is read-only: c = 'x'; inside the loop is a compile error, because c is a foreach iteration variable.
    • Single quotes and double quotes. '7' is a char, one character, while "7" is a string. char.IsDigit takes a char.
    • The ternary operator. hasDigit ? "True" : "False" picks the first text when hasDigit is true and the second when it is false. The parentheses around it matter. Written as "Has digit: " + hasDigit ? "True" : "False", the + is evaluated first, which leaves a string as the condition, and the compiler rejects it with Cannot implicitly convert type 'string' to 'bool'.
    • A bool already prints as True. In C#, "Has digit: " + hasDigit produces Has digit: True or Has digit: False, with capital letters. The ternary spells out the text so the output doesn't depend on that formatting, and it is the pattern for printing any wording you choose, such as Yes and No.
    • && short-circuits. If length >= 8 is false, C# does not look at hasDigit, because the whole condition is already false. Here that changes nothing, since hasDigit is a plain variable, but it matters when the right side is a method call.

    Stopping early and shorter forms

    Once a digit is found, the remaining characters can't change the answer. Adding break; after hasDigit = true; ends the loop at that point. For "Secret99" the loop would stop at the first 9, the seventh character, instead of visiting all eight. The lesson's version keeps the plain loop, which is simpler to read and costs nothing noticeable on a short text. C# also has a one-line form, password.Any(char.IsDigit), from the System.Linq namespace, but the explicit loop shows what that call does.

    What counts as a digit

    char.IsDigit is true for the decimal digits of any writing system, not only 0 to 9. For example, char.IsDigit('٣') (the Arabic-Indic digit three) is true. For this lesson that is fine. If you ever need to accept only the ASCII digits, test the range instead: c >= '0' && c <= '9'.

    Edge cases and common mistakes

    • Long but no digit. "abcdefgh" passes the length rule and fails the digit rule, so it is Weak.
    • Digit but short. "a1" has a digit and a length of 2, so it is Weak.
    • Resetting the flag in the loop. An else { hasDigit = false; } would let the last character decide the answer, and "1abcdefg" would be reported as having no digit. The flag only ever changes in one direction.
    • Printing inside the loop. A Console.WriteLine for the flag inside the braces would print once per character, eight lines for an 8-character password.
    • Using || instead of &&. That would call a password strong when it satisfies either rule, so "abcdefgh" would be Strong.
    • Empty password. "" never enters the loop, so hasDigit stays false and the output is Length: 0, Has digit: False, Weak.

    Testing

    • "Secret99" gives Length: 8, Has digit: True, Strong.
    • "abcdefgh" gives Length: 8, Has digit: False, Weak.
    • "a1" gives Length: 2, Has digit: True, Weak.
    • "1abcdefg" gives Length: 8, Has digit: True, Strong.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free