CSc 1301
Lab #11 – while loops; char, String, int; type casting
Example:
· Write a method digitSum that accepts an integer parameter and returns the sum of its digits.
· Assume that the number is non-negative.
· Example: digitSum XXXXXXXXXXreturns XXXXXXXXXXor 19
· Hint: Use the % operator to extract a digit from a number.
IMPORTANT: you should have practiced very similar problem before, but because given number was said to have exactly 5 digits, you used for loops for that. Now you should make your solution suitable for ANY number, and therefore while loop makes more sense. Also, be ready to handle negative numbers.
Solution:
public static int digitSum(int n) {
n = Math.abs(n);
handle negatives
int sum = 0;
while (n > 0) {
XXXXXXXXXXsum = sum + (n % 10);
add last digit
XXXXXXXXXXn = n / 10;
remove last digit
}
return sum;
}
Additional Examples:
1.
2.
3.
4.
Problem 1.
Write a method called showTwos that shows the factors of 2 in a given random integer in the range of [16,128] (by using of while loop). For example, consider the following calls:
showTwos(7);
showTwos(18);
showTwos(68);
showTwos(120);
These calls should produce the following output:
7 = 7
18 = 2 * 9
68 = 2 * 2 * 17
120 = 2 * 2 * 2 * 15
Problem 2.
Recall how char and int are related:
'A' is 65 'B' is 66 ' ' is 32
'a' is 97 'b' is 98 '*' is 42
What will be the output? Consider each printing statement separately.
System.out.println(‘b’ + “abc” + 22);
prints
System.out.println(“abc” + 22 + ‘b’);
prints
System.out.println(22 + ‘b’ + “abc”);
prints
System.out.println(22 + “abc” + ‘b’);
prints
System.out.println(‘b’ + “b”);
prints
System.out.println(‘a’-11+22);
prints
System.out.println(‘a’ * 3 +2);
prints
System.out.println((char) 42);
prints
System.out.println((char) 69);
prints
System.out.println((char) 100);
prints
Problem 3.
What will be the output? Consider each printing statement separately.
String sentence = "Good Morning, America";
char symbol = sentence.charAt(10);
System.out.println(symbol);
prints
System.out.println(sentence + symbol + “!”);
prints
System.out.println(symbol + symbol);
prints
System.out.println(sentence.substring(3,7));
prints
System.out.println(sentence.substring(2,4));
prints
Page 2 of 5