89.5k views
4 votes
Java

Write a program, name it Alpha2DArray, that will fill a 2D array with the letters of the alphabet "a-z" in row major order (i.e. left-right, top-down as you would read a book.) Once the letter "z" is reached, the cycle begins again with an "a" until all elements of the 2D array are filled. Print your array after using nested for loops to test your result. The program should work for any size 2D array.

User BrezzaP
by
8.5k points

1 Answer

4 votes

Final answer:

The Alpha2DArray program in Java creates a 2D array and fills it with the alphabet in row-major order, wrapping from 'z' back to 'a'. Nested loops are used to populate and print the array. The provided example demonstrates how to implement and display this in a 5x5 array.

Step-by-step explanation:

The Alpha2DArray program in Java fills a 2D array with the letters of the alphabet in row-major order and prints the array. To ensure the program works for any given size of the 2D array, nested for loops are used to iterate through each element of the array. When the letter 'z' is reached, the insertion starts again at 'a' and continues until the array is completely filled.

Here's an example of how the code may look:

public class Alpha2DArray {
public static void main(String[] args) {
char[][] array = new char[5][5]; // Example size of 5x5
char letter = 'a';

for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = letter++;
if (letter > 'z') {
letter = 'a';
}
}
}

// Printing the 2D array
for (char[] row : array) {
for (char ch : row) {
System.out.print(ch + " ");
}
System.out.println();
}
}
}

This code snippet initializes a 5x5 2D array and fills it with the alphabet sequence, handling the wrap-around from 'z' to 'a' using a simple if condition inside the nested loops. The resulting array is then printed to the console.

User JDJ
by
8.1k points

No related questions found