I have to print a 5×5 table with alphabets in them, like:
<table>
<tr> <td>A</td> <td>B</td> <td>C</td> <td>D</td> <td>D</td>
etc.. the letters are in fact a link, so they will be like:
<td> <a href='/someplace'>A</a> </td>
Those links have all the tendency to change often and I don’t fancy hard-coding them and replacing them since they will be appearing in quite a few pages. So I thought I would write up a function to output the whole structure.
Yes, it’s pretty straight forward, get the for loop to behave like:
StringBuilder alphabets = new StringBuilder("<table class='table'>");
for(int i=65; i<=87; i++)
{
//Do stuff here to calculate if i mod 5 is zero and add <tr> accordingly.
//Use Convert.ToChar(i); to get the wanted structure.
}
Then it hit me, I could possibly do it in a better, “clever” way using nested for loops,
for(i=1; i<=5; i++)
{
alpbahets.Append("<tr>")
for(j=1; j<5; j++)
{
//Get the <a > link string here.
}
alphabets.Append("</tr");
}
Now the question is, what can I do to relate i AND j to get them into the range of 65-87?
(A-W, since it’s a 5×5 grid I will skip the last iteration and manually add YZ in one td).
I have tried (i*10 + j) + 54) (yea, I don’t know what I was thinking), but it doesn’t work.
This might be an EXTREMELY stupid question, sorry, but what is the way to get this done in nested for loops? Or is there any other better way? I am asking because I am very curious to know more (and dumb that I already don’t).
What about just introducing a variable
char letter = 'A';out side your loops?Then after using it, call
letter++;to move to the next letter in the alphabeth.This will make your program more readable also, and won’t force other programmers to see some calculation including i and j that ends up as a letter.
Simplicity is often the best solution 🙂