Java: Print the contents of a two-dimensional Boolean array in specific format
Java Basic: Exercise-154 with Solution
Write a Java program to print the contents of a two-dimensional Boolean array where t represents true and f represents false.
Sample array:
array = {{true, false, true},
{false, true, false}};
Visual Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
// Creating a 2D boolean array with initial values
boolean[][] array = {{true, false, true},
{false, true, false}};
// Finding the number of rows in the array
int rows_length = array.length;
// Finding the number of columns in the array by considering the length of the first row
int columns_length = array[0].length;
// Looping through each element of the 2D array
for (int i = 0; i < rows_length; i++) {
for (int j = 0; j < columns_length; j++) {
// Checking if the current element is true or false and printing accordingly
if (array[i][j]) {
System.out.print(" t "); // Printing " t " if true
} else {
System.out.print(" f "); // Printing " f " if false
}
}
System.out.println(); // Moving to the next line after printing each row
}
}
}
Sample Output:
t f t f t f
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program that accepts two double variables and test if both strictly between 0 and 1 and false otherwise.
Next: Write a Java program to print an array after changing the rows and columns of a given two-dimensional array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/basic/java-basic-exercise-154.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics