TM105
Exercises on Meeting 4
Q1. What will be printed after executing the following Java statements?
a) [Link]( [Link](-3.5));
b) [Link]([Link](3.5));
c) [Link]( [Link](3.5));
d) [Link]( [Link](3.45));
e) [Link]([Link](-2.5, -3.5));
f) [Link]([Link](3, 2));
g) [Link]([Link](4));
h) [Link]([Link](4.9));
i) [Link]([Link](4.9));
j) [Link]([Link](-4.9));
k) [Link]([Link](-4.9));
Q2. What is the exact output of the following pieces of code?
1)
int i = 1;
while (i >= 3) {
[Link]('*'); i++;
}
[Link]("i = " + i);
2)
int i = 1;
while (i <= 3)
{
[Link]('*');
i++;
}
[Link](i);
3)
int i;
for (i = 0; i < 3; i++)
[Link]("*");
[Link]("\ni = " + i);
1
4)
int i;
for (i = 1; i <= 3; i++)
{
[Link]("*");
[Link](i);
}
[Link]("i = " + i);
5)
int i=4;
while (i >= 1)
i--;
[Link](i);
6)
int i=4;
while (i >= 1)
{
i--;
[Link](i);
}
Q3. Modify the following code such that for is used instead of the while statement:
int i = 10;
while (i > 0)
{
[Link](i);
i--;
}
[Link]("Done");
Q4. Modify the following code such that while is used instead of the for statement:
for (int i = 1;i<=10; i+=2)
[Link](i);
[Link]("Done");
2
Q5. Write Java programs to do the following:
1. Read from the user a real number that represents the length of the side
opposite the 30-degree angle in a 30-60-90 triangle (x). The program then
calculates and prints the area of this triangle (rounded to 2 decimal places)
according to the following formula:
𝑎𝑟𝑒𝑎 = (√3𝑥 )
2. Prompt the user to enter 2 integers and print the sum of all even numbers between these 2
integers (inclusive). Assume that the first integer is always less than or equal to the second
integer.
3. Prompt the user to 10 integers. The program should count and print the number of positive
integers, negative integers and zeros entered by the user.
4. Prompt the user to enter 10 positive integers. The program should count and print the
maximum and minimum integers entered by the user. Assume that the integers will be from
0 to 1000.
5. Prompt the user to enter integers (0 to stop). The program should count and print the
number of positive integers and the number of negative integers.
6. Prompt the user to enter laptops’ brands owned by a company (“Done” to stop). The
program should count and print the number of Dell laptops available in addition to the total
number of laptops entered.
7. Prompt the user to enter a positive integer, then separate the integer into its individual digits
and print a message indicating if the sum of its digits is odd or even.
Example: if the user enters 35271, the output should be:
The sum of the digits of 35271 is 18, which is even.
Explanation: 3 + 5 + 2 + 7 + 1 = 18 which is even.
8. Read from the user 2 integers, then display on the screen a rectangle of asterisks its number
of rows is the first integer and its number of columns is the second integer. Assume that the
user will enter positive integers.
Example: if the user enters 3 and 7, the output should be:
*******
*******
*******