In: Computer Science
Using Java, write a program that takes in two integers from the keyboard called m and n, where m > n. Your program should print the first m natural numbers (m..1) downwards in n rows.
Here is the code:
import java.util.*;
import java.io.*;
class PrintNums {
//ceiling function for m/n
public static int ceil(int m, int n) {
//if m is divisible by n
if (m % n == 0) return m/n;
else return m/n + 1;
}
public static void main (String[] args) {
//take input
int m, n;
System.out.print("Enter m,n(m>n): ");
Scanner sc = new Scanner(System.in);
m = sc.nextInt();
n = sc.nextInt();
//each row will contain at most ceil(m/n) elements
int elsInRow = ceil(m, n);
//create a row
for (int i=0; i<n; i++) {
//print at most ceil(m,n) elements
for (int j=0; j<elsInRow && m>0; j++) {
//print m and decrease it
System.out.print(m--+" ");
}
//print a newline
System.out.println();
}
}
}
Here is a screenshot of the code:
Here is a screenshot of the output:
Comment in case of any doubts.