You can nest loops by writing one within the other.
For example, the next piece of code prints the phrase "hello, world!"
n x m times
// often known as an outer loop
for (int i = 0; i < n; i++)
{
// often known as a nested loop
for (int j = 0; j < m; j++)
{
printf("hello, world!\n");
}
}
What you need to do in vigenere is that you should cipher each character in the plaintext (e.g., "Meet me at the park at eleven am"
) using the current key from the keyword (e.g., "bacon"
).
Logically, we need to iterate over each of the characters in plaintext
exactly once to cipher it. One way to do that is by writing something like
for (int i = 0, length = strlen(plaintext); i < length; i++)
{
// do something
}
Now, for each character of these, we need to use the current key from the keyword
to cipher it. And we don't really need to use a second loop for that!
We can have a variable to store the index
of the current key in the keyword
(e.g., 0
in case it's b
or 2
in case it's c
considering "bacon"
). Then we can cipher our current character in plaintext
using keyword[index]
, but we'll have to care about index
exceeding keyword
's boundaries.
You may have a look at this answer to get some sort of an idea of how you can take handle that!
Update: here's some pseudocode to make things easier for you
for (int i = 0, pl = strlen(plaintext), kl = strlen(keyword), index = 0 to i < pl, i++)
{
declare a char named current and set it to plaintext[i]
if (current is an alphabetical char)
{
if (current is a lowercase char)
{
cipher current using keyword[index % kl] appropriately
}
else
{
cipher current using keyword[index % kl] appropriately
}
increment index by 1
}
print current
}