Example sheet 3
1. For a number n, the factorial of n (factoral(n), or n!) is the product of all the whole numbers between 1 and n (inclusive). So, for example,
factorial(3) = 1 x 2 x 3 = 6
factorial(4) = 1 x 2 x 3 x 4 = 24 factorial(10) = 1 x 2 x … x10 = 3628800
Copyright By PowCoder代写 加微信 powcoder
The following code contains 3 methods which calculate the factorial of a number n using a do loop, a while loop and a for loop respectively:
public static int factorial1(int n){ //use a do-while loop
int top = n;
int prod = 1;
do{prod = prod*top; top–;
} while (top > 1);
return prod; }
public static int factorial2(int n){ // use a while loop
int top = n;
int prod = 1;
while(top>1){
prod = prod*top;
return prod; }
public static int factorial3(int n){
// use a for loop
int prod = 1;
for(int top =n; top>1; top –) prod = prod*top; return prod;
(a) Look at each of the methods carefully and try each with a few different values of n to check that they return the correct value
(b) Write three methods of your own, sum1, sum2 and sum3, each calculating the sum of the first n whole numbers (>0) that are divisible by 3. So for example, for n=4 your methods should return the value 30 (i.e. 3+6+9+12). Like the examples above, your methods should use a do loop, a while loop and a f or loop respectively.
In the previous example, there wasn’t much difference between the do and while loops. Consider instead the following methods:
public static void danger1(){ boolean alligator = true;
boolean safe = true; do{//swim in rock pool
if(alligator){
System.out.println(”eaten by alligator”);
safe=false; }
while(alligator==false) ;
if(safe) System.out.println(”still alive!”);
public static void danger2(){ boolean alligator = true;
boolean safe = true; while(alligator==false) {
//swim in rock pool
if(alligator){
System.out.println(”eaten by alligator”);
safe=false; }
if(safe) System.out.println(”still alive!”);
In each case, what would happen if the method was called?
3. In the lecture you have learned about string formatting. Here are some of the examples that you saw (where “~” denotes space).
Format specifier: %15s
%5d %-5d %05d %5.2f
Applied to: “Bill” “Cuthbert” “Bill”
gives: “~~~~~~~~~~~Bill” “~~~~~~~Cuthbert” “Bill~~~~~~~~~~~” “~~~23”
Fill in the right hand column of the table below:
Format specifier: %14s
%6d %-6d %06d %2d %6.2f %6.3f %6.4f %10.6f
Applied to: “Annabelle” “Annabelle” “Annabelle” 145
145 145 145 22.167 22.167 22.167 22.167
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com