关键词 > 159.234
159.234 OBJECT-ORIENTED PROGRAMMING TUTORIAL 2
发布时间:2023-06-13
Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit
159.234 OBJECT-ORIENTED PROGRAMMING
Tutorial 2
Task 1: Review the content of Lecture 05 _ Java Control Structures, answer the following questions:
1. What is the main difference between a while loop and a do..while loop?
Both types of loops repeat a block of statements until some condition becomes false. The main difference is that in a while loop, the condition is tested at the beginning of the loop, and in a do…while loop, the condition is tested at the end of the loop. It is possible that the body of a while loop might not be executed at all. However, the body of a do…while loop is executed at least once since the condition for ending the loop is not tested until the body of the loop has been executed.
2. Write a for loop that will print out all the multiples of 3 from 3 to 36, that is: 3 6 9 12 15 18 21 24 27 30 33 36.
Here are two possible answers. Assume that N has been declared to be a variable of type int:
for ( N = 3; N <= 36; N = N + 3 ) {
System.out.println( N );
}
or
if ( N % 3 == 0 )
System.out.println( N );
}
3. Suppose that numbers is an array of type int[]. Write a code segment that will count and output the number of times that the number 42 occurs in the array.
Use a for loop to go through the array and test each array element. If the value is 42, add 1 to a counter:
int count42; // The number of 42s in the array
count42 = 0;
int i; // loop control variable
for ( i = 0; i < numbers.length; i++ ) {
if ( numbers[i] == 42 ) {
count42++;
}
}
System.out.println("There were " + count42 + " 42s in the array.")