Pavan Kotti
Computer Science
[Link]
Chapter 4 Book Problems
p304 27,28,29. p305: 2, 4, 6, 7, 8
27.
4, 2, 5 would fail as a set of numbers in the code given
One way to improve the given code would be to turn it in to a if else statements and make the
conditionals more clearer compared to using a nest loop
28.
If the given number t is a negative the code would fail
A solution that would work would be by putting an if statement at the beginning of the code to
check for any negatives and this would effectively end the code at the start if any negative
numbers were given
29.
an odd number would be the only type of number that would work in this code
For this to work properly user needs to change all the if else statements into if statements or the
user could just return.\ if used in the right way and location
2.
public static String repl(String x, int rep) {
String str = "";
int s = 0;
for (int i = 0; i < rep; i++) {
s += x;
}
[Link](s);
}
4.
public static int daysInMonth(int a) {
if (a == 1 || a == 3 || a == 5 || a == 7 || a == 8 || a == 10 || a == 12) {
[Link](“31”);
} else if (a == 2) {
[Link](“28”);
} else { //this would just be the rest of the month could also write them out but an else
statement is easier
[Link](“30”);
}
}
6.
public static void printrange(int num, int num1) {
if (num < num1) {
for (int i = num; i <= num1; i++) {
[Link](i + " "); }
} else {
for (int i = num; i >= num1; i--) {
[Link](i + " "); }
}
}
8.
public static void smallestLargest() {
Scanner s = new Scanner([Link]); //created to get the user input
[Link]("How many numbers do you want to enter? ");
int numAmunt = [Link]();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 1; i <= numAmount; i++) {
[Link]("Number " + i + ": ");
int number1 = [Link]();
if (number2 < min) {
min = number1;
}
if (number > max) {
max = number1; }
}
[Link]("Smallest number = " + min); //prints min
[Link]("Largest number = " + max); // prints max
}