Nicholas Zachariah :
I am trying to come up with the following output:
Row 1 Col A
Row 1 Col B
Row 2 Col A
Row 2 Col B
I am having trouble figuring out the logic to complete this task. So far I came up with the code provided below:
int iRowNum;
int iColLetter;
iRowNum = 1;
iColLetter = 65;
while (iColLetter < 67)
{
System.out.println("Row " + iRowNum + " Col " + (char)iColLetter);
iColLetter++;
while (iRowNum < 3)
{
iRowNum += 1;
}
}
Unfortunately, I receive the output of:
Row 1 Col A
Row 3 Col B
That begin said, I have a feeling I am getting close to where I need to be, but I spent a good chunk of time trying to figure out the logic behind my desired output.
Final Question How do I display the rows and columns as shown in the first block of this post?
Arvind Kumar Avinash :
Do it as follows:
public class Main {
public static void main(String[] args) {
int iRowNum = 1;
int iColLetter = 65;
while (iRowNum < 3) {
iColLetter = 65;
while (iColLetter < 67) {
System.out.println("Row " + iRowNum + " Col " + (char) iColLetter);
iColLetter++;
}
iRowNum += 1;
}
}
}
Output:
Row 1 Col A
Row 1 Col B
Row 2 Col A
Row 2 Col B
Explanation:
- Since you want the
iRowNum
to go up to2
, you start withwhile (iRowNum < 3)
orwhile (iRowNum <= 2)
. - For each value of
iRowNum
, the inner loop has to run for two times, starting with65
i.e. you need to resetiColLetter
to65
before the start of the inner loop.