Alphabet string code, looping

131 views Asked by At

So I need to finish this program that asks user to type in a word and then he needs to write it back "encrypted", only in number.
So a is 1, b is 2...
For example if I give the word "bad", it should come back as "2 1 4".
The program I made seems to do this always only for the 1st letter of the word.
My question that I would need help with is, why does this program stop looping after the 1st letter? Am I even doin it right or is it completely off?
Any help would be much appreciated.

        Console.Write("Please, type in a word: "); 
        string start = Console.ReadLine();

        string alphabet = "abcdefghijklmnopqrstuvwxyz";

        for (int c = 0; c < alphabet.Length; c++)
        {
            int a = 0;

            if (start[a] == alphabet[c])
            {
                Console.Write(c + 1);
                a++;
                continue;
            }
            if (start[a] != alphabet[c])
            { 
                a++;
                continue;
            }

        }
1

There are 1 answers

1
Dan Hogan On BEST ANSWER

I accomplished it with a nested loop:

Console.Write("Please, type in a word: ");
string start = Console.ReadLine();

string alphabet = "abcdefghijklmnopqrstuvwxyz";

for (int a = 0; a < start.Length; a++)
{
    for (int c = 0; c < alphabet.Length; c++)
    {
        if (start[a] == alphabet[c])
        {
            Console.Write(c + 1);
        }
    }
}

While comparing the strings, it makes sense, at least to me, to loop through both of them.

Your program was stopping after the first letter because your were resetting "a" to 0 at the beginning of every loop.