recursion - write and test a method PrintSquare -
write , test method printsquares has integer parameter n, , prints squares of integers 1 n, separated commas. should print squares of odd integers in descending order first , following squares of integers in ascending order. not print newline character. should throw illegalargumentexception if specified integer less 1. example: printsquares(4) should print 9, 1, 4, 16 printsquares(1) should print 1 printsquares(7) should print 49, 25, 9, 1, 4, 16
there go, hope teacher ok (this throw exceptions if enter negetive numbers , adds useless comma @ end can fix if bothers you)
public static void printorder(int n) { decorderodd(n); acsordereven(1, n); } public static void decorderodd(int n) { if (n > 0) { if (n%2 == 1) { system.out.print(n*n + ", "); decorderodd(n-2); } if (n%2 == 0) decorderodd(n-1); } } public static void acsordereven(int n, int target) { if (n <= target) { if (n%2 == 0) { system.out.print(n*n + ", "); acsordereven(n + 2, target); } if (n%2 == 1) acsordereven(n+1, target); } }
Comments
Post a Comment