Posts

Showing posts from March, 2020

Print staircase with both base and height equal to n

Consider a staircase of size n=4, as shown below:       #     ##   ### #### Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size n. public static void main(String[] args) { int n = 10; if(n < 1 || n > 100) { throw new IllegalArgumentException("N should be between 0 and 100"); } for (int i = 1; i <= n; i++) { System.out.println(Stream.concat(Stream.generate(() -> " ").limit(n-i), Stream.generate(() -> "#").limit(i)) .collect(Collectors.joining())); } } }

Given an n x n square matrix, find sum of all sub-squares of size k x k

Solution: for (int i = 0; i < n-k+1; i++) { for (int j = 0; j < n-k+1; j++) { int sum = 0; for (int p = i; p < k+i; p++) for (int q = j; q < k+j; q++) sum += mat[p][q]; } }