w3resource

Java: Print the contents of a two-dimensional Boolean array in specific format


Print Boolean Matrix

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:

Java Basic Exercises: Print the contents of a two-dimensional Boolean array in specific format.


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:

Flowchart: Java exercises: Print the contents of a two-dimensional Boolean array in specific format.



For more Practice: Solve these Related Problems:

  • Write a Java program to print a 2D Boolean array with row and column indices alongside each value.
  • Write a Java program to print a 2D Boolean matrix where true values are displayed as 'F' and false values as 'T'.
  • Write a Java program to print a 2D Boolean array in reverse order (i.e., bottom-up row order).
  • Write a Java program to count the number of true values in a 2D Boolean array and then print the matrix.

Go to:


PREV : Test Doubles Between 0 and 1.
NEXT : Transpose 2D Array.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.