Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

Unity university

College of computer science


Object oriented programing
Individual Assignment

Done By: Adam Wondale


ID: UU89419R
Section: n4

Submission date: Dec, 30, 2023


Submitted to: Mr. Mezgebe M.
A) The loop body is not repeated at all because the condition of the while loop is i>10, and i is
initially 1, which does not satisfy the condition.
B) The loop body will be repeated 9 times. The iteration steps are:

1. i = 1: The loop condition is true, and i is printed since it is an odd number.


2. i = 2: The loop condition is true, but i is not printed since it is an even number.
3. i = 3: The loop condition is true, and i is printed since it is an odd number.
4. i = 4: The loop condition is true, but i is not printed since it is an even number.
5. i = 5: The loop condition is true, and i is printed since it is an odd number.
6. i = 6: The loop condition is true, but i is not printed since it is an even number.
7. i = 7: The loop condition is true, and i is printed since it is an odd number.
8. i = 8: The loop condition is true, but i is not printed since it is an even number.
9. i = 9: The loop condition is true, and i is printed since it is an odd number.
Therefore, the output would be

3
5
7
9
1. The main difference between a while loop and a do-while loop is that a while loop
may not execute its block at all if the condition is false initially, while a do-while loop
will always execute its block at least once before checking the condition.
2. In Java, we cannot directly cast between a boolean and an integer. However, you can
use conditional expressions to achieve similar results.
boolean b = true;
int i = b ? 1 : 0; // Convert boolean to int using conditional expression
System.out.println(i); // Output: 1

Or

int i = 1;
boolean b = i != 0; // Convert int to boolean using conditional expression
System.out.println(b); // Output: true
3. Both loops will produce the same result in sum. The choice between using i++ or ++i
does not affect the outcome.
4. In Java, a for loop consists of three parts: the initialization, the condition, and the
increment/decrement.
1. Initialization: This part is executed only once at the beginning of the loop. It
initializes the loop control variable to a starting value.
2. Condition: This part is evaluated before each iteration of the loop. If the condition
is true, the loop body is executed. If the condition is false, the loop terminates.
3. Increment/Decrement: This part is executed after each iteration of the loop. It
updates the loop control variable to a new value.
 a for loop that prints the numbers from 1 to 100.

for (int i = 1; i <= 100; i++) {


System.out.println(i);
}
5. for ( ; ; ) {
do something;
}
This represents an infinite loop in Java. An infinite loop is a loop that continues
indefinitely until a specific condition is met or until the program is terminated externally.
In this case, the loop has no initialization, condition, or update statement, resulting in an
endless repetition of the code block within the loop.

6. In Java, the scope of a variable declared in the control section of a for loop is limited
to the loop itself. Once the loop exits, the variable is no longer accessible.
7. Yes, for loops can be converted in to while and do while loops.
 for loops offer simplicity, controlled iteration, efficiency, and convenience when
working with arrays and collections in Java. They are a powerful tool for handling
repetitive tasks.
8. Converting the following for loop statement to a while loop and to a do-while loop:

long sum = 0;
for (int i =0; i <=1000; i++)
sum = sum + i;
while loop
long sum = 0;
int i = 0;
while (i <= 1000) {
sum += i;
i++;
}
do while loop

long sum = 0;
int i = 0;
do {
sum += i;
i++;
} while (i <= 1000);

9. The "break" keyword is used to terminate the execution of a loop or switch statement.
When encountered, it immediately exits the loop or switch statement and continues
with the next statement after the loop or switch.

The "continue" keyword is used to skip the rest of the current iteration of a loop and
move on to the next iteration. It allows you to bypass certain statements within a loop
based on a condition, without terminating the loop entirely.

Will the following program terminate? If so, give the output.

 int balance =1000;


while (true) {
if(balance <9)
break;
balance = balance = 9;
}
System.out.println("balance is "+ x);

 int balance =1000;


while (true) {
if(balance <9)
continue;
balance = balance = 9;
}
System.out.println("balance is "+ x);
The given program will not terminate. The condition while (true) creates an infinite loop
and there is no way to exit the loop because the break statement is inside an if block, and
“break” will never be executed because the condition in the if statement will never be
true and the loop will continue indefinitely.

As a result, the program will not produce any output.

And the same goes to the second with the continue statement!

10. int sum = 0;


for (int i = 1; sum < 10000; i++){
sum = sum + i;
}

11. the problem with the converted code it the “continue” statement and that cause the
incrementation(i++) code to not be reached which result infinite loop

the correct conversion would be

 int i = 0;
int sum = 0;
while (i < 4) {
if (i % 3 == 0) {
i++;
} else {
sum += i;
System.out.println(sum);
i++;
}
}
12. After the break outer; statement is executed in the inner loop, the next statement to be
executed would be the next: statement. This is because the break outer; statement
causes the program to exit both the inner and outer loops, and control will resume at the
statement following the outer loop, which is the next: statement.

13. After the continue outer; statement is executed in the inner loop, the next statement to
be executed would be the next: statement. This is because the continue outer; statement
causes the program to skip the rest of the inner loop and start the next iteration of the
outer loop, and control will resume at the statement following the outer loop, which is
the next: statement.
14. The fixed error code

public class Test {


public static void main(String[] args) {
int sum = 0;
int j = 0;

for (int i = 0; i < 10; i++) {


sum += i;
}

if (i < j) {
System.out.println(i);
} else {
System.out.println(j);
}

while (j < 10) {


j++;
}

do {
j++;
} while (j < 10);
}
}
15. A) the error is i is not initialized

B) there is no error.

16. A) 0 0 1 0 1 2 0 1 2 3
B)
*****
*****
2 *****
3 2 *****
4 3 2 *****
C)
1xxx2xxx4xxx8xxx16xxx
1xxx2xxx4xxx8xxx
1xxx2xxx4xxx
1xxx2xxx
1xxx
D)
1G
1G3G
1G3G5G
1G3G5G7G
1G3G5G7G9G
17. The Math.random() method in Java returns a double value greater than or equal to 0.0
and less than 1.0. Therefore, the possible outputs from invoking Math.random() are
within the range of 0.0 (inclusive) to 1.0 (exclusive).

So, out of the options :


- 0.5 is a possible output from invoking Math.random()
- 1.0 is not a possible output because it's not less than 1.0
- 0.0 is a possible output from invoking Math.random()
- 0.234 is a possible output from invoking Math.random()

323.4 and 34 are outside the range of values that Math.random() can return, so they are
not possible outputs.
18. The issue with the code is that the conditions for assigning grades are not in the correct
order. The conditions should be arranged in descending order, from highest to lowest,
to ensure that the correct grade is assigned based on the score.
19. To rewrite the statement using a Boolean expression, we can directly assign the result
of the comparison to the newLine variable.
newLine = (count % 10 == 0);
20.
 (true) && (3 > 4)
Result: true && false
The result is false.

 !(x > 0) && (x > 0)


Result: !(1 > 0) && (1 > 0)
This simplifies to: false && true
The result is false.

 (x > 0) || (x < 0)
Result: (1 > 0) || (1 < 0)
This simplifies to: true || false
The result is true.

 (x != 0) || (x == 0)
Result: (1 != 0) || (1 == 0)
This simplifies to: true || false
The result is true.

 (x >= 0) || (x < 0)
Result: (1 >= 0) || (1 < 0)
This simplifies to: true || false
The result is true.

 (x != 1) == !(x == 1)
Result: (1 != 1) == !(1 == 1)
This simplifies to: false == false
The result is true.
21.
(x < y && y < z) is true
(x < y || y < z) is true
!(x < y) is false
(x + y < z) is true
(x + y < z) is true
22. The value of y will be 2. Since there is no break statement the program goes to default .
23. Using switch statement
switch (a) {
case 1:
x += 5;
break;
case 2:
x += 10;
break;
case 3:
x += 16;
break;
case 4:
x += 34;
break;
}

The flow chart of the switch statement


24.
public class DayNameAssigner {
public static void main(String[] args) {
int day = 3; // Example value for day

String dayName;

switch (day) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
break;
}

System.out.println("The day name is: " + dayName);


}
}

25. System.out.print(count % 10 == 0 ? count + "\n" : count + " ");

26.
- Boolean value: %b
- Character: %c
- Decimal integer: %d
- Floating-point number: %f
- String: %s

27.
A) The number of arguments does not match the number of placeholders in the format
string.
B): The number of arguments does not match the number of placeholders in the format
string.
C) There is no error.
28. A) amount is 32.320000 3.232000e+01
B) amount is 32.3200 3.2320e+01
C) false
D) Java
E) false Java
F) falseJava
29.
In Java, the precedence order of Boolean operators is as follows:
1. Logical NOT (!)
2. Logical AND (&&)
3. Logical OR (||)

Evaluating the given expressions:

true || true && false:

 According to the precedence order, the && operator has higher precedence than ||. So,
the expression is evaluated as follows:

true && false is evaluated first, resulting in false.


Then, true || false is evaluated, resulting in true.
Therefore, the value of the expression true || true && false is true.

true && true || false:

 Both && and || operators have the same precedence. So, the expression is evaluated
from left to right:

true && true is evaluated first, resulting in true.


Then, true || false is evaluated, resulting in true.
Therefore, the value of the expression true && true || false is true.
30. Identifying the errors
 The main method should be declared as public static void main(String[] args). The
static keyword is required for the main method to be the entry point of the program.

 The semicolon at the end of line 3 (for (int i = 0; i < 10; i++);) should be removed.
Otherwise, the loop will not execute any statements.

 The variable sum is not declared or initialized before being used in line 4 (sum += i;).
You need to declare and initialize it before using it in the loop.

 The semicolon at the end of line 6 (if (i < j);) should be removed. Otherwise, the if
statement will not execute any statements.

 The semicolon at the end of line 11 (while (j < 10);) should be removed. Otherwise,
the while loop will not execute any statements.

 The semicolon at the end of line 14 (j++;) should be removed. Otherwise, the
increment statement will not be executed in the while loop.

 The semicolon at the end of line 18 (} while (j < 10)) should be replaced with a
semicolon. Otherwise, the do-while loop will not execute any statements.
The fixed code
public class Test {
public static void main(String[] args) {
int sum = 0;
int j = 0;
for (int i = 0; i < 10; i++) {
sum += i;
}
if (i < j) {
System.out.println(i);
} else {
System.out.println(j);
}
while (j < 10) {
j++;
}
do {
j++;
} while (j < 10);} }
31. After the continue statement is executed in the nested loop, the control goes back to
the beginning of the inner loop. The continue statement skips the remaining code in
the inner loop for the current iteration and moves on to the next iteration.
The output:
1
2
1
2
2
3

32. After the break statement is executed in the nested loop, the control flow will exit the
innermost loop and continue with the next iteration of the outer loop. The break
statement terminates the inner loop prematurely when the condition i * j > 2 is met.
The output:
1
2
1
2
2
3
33. yes we can always convert while loop to for loop
the converted for loop
int sum = 0;
for (int i = 1; sum < 10000; i++) {
sum = sum + i;
}
34.
Will the following program terminate? If so, give the output.

 int balance =1000;


while (true) {
if(balance <9)
break;
balance = balance - 9;
}
System.out.println("balance is "+ x);

 int balance =1000;


while (true) {
if(balance <9)
continue;
balance = balance - 9;
}
System.out.println("balance is "+ x);

 The first program will terminate, and the output will be "balance is 1".
 The second program will not terminate because it contains an infinite loop.
here is a condition if (balance < 9) continue; which uses the continue statement. This
statement will skip the remaining code in the loop and start the next iteration if the
condition is true. Since the initial value of balance is 1000, which is greater than 9,
the continue statement will not be executed.

35. The out would be


 max is 5
number 0
Programming Exercises
36. Pattern (a)

int rows = 6;

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Pattern (b)

int rows = 6;

for (int i = rows; i >= 1; i--) {


for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Pattern (C)

int rows = 6;

for (int i = 1; i <= rows; i++) {


for (int j = rows - i; j > 0; j--) {
System.out.print(" ");
}
for (int k = i; k > 0; k--) {
System.out.print(k + " ");
}
System.out.println();
}
Pattern ( D )

int rows = 6;

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 6 - i + 1; k++) {
System.out.print(k + " ");
}
System.out.println();
}
37.
for (int row = 0; row < 8; row++) {
for (int column = 1; column < 8 - row; column++) {
System.out.print(" ");
}

for (int column = 0; column <= row; column++) {


System.out.print(" " + (int)Math.pow(2, column));
}

for (int column = row - 1; column >= 0; column--) {


System.out.print(" " + (int)Math.pow(2, column));
}

System.out.println();
}
38.
import java.util.Scanner;
public class DaysInMonth {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the month (1-12): ");
int month = input.nextInt();
String mon ="";

System.out.print("Enter the year: ");


int year = input.nextInt();
int days = 0;

switch (month) {
case 1: // January
mon = "January";
case 3: // March
mon = "March";
case 5: // May
mon = "May";
case 7: // July
mon = "July";
case 8: // August
mon = "August";
case 10: // October
mon = "October";
case 12: // December
mon = "December";
days = 31;
break;
case 4: // April
mon = "April";
case 6: // June
mon = "June";
case 9: // September
mon = "September";
case 11: // November
mon = "November";
days = 30;
break;
case 2: // February
mon ="February";
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
default:
System.out.println("Invalid month.");
System.exit(0);
}

System.out.println(mon +" " + year + " has " + days + " days."); }}
39.
public class RandomUppercaseLetter {
public static void main(String[] args) {
char randomUppercaseLetter = (char) ('A' + Math.random() * ('Z' - 'A' + 1));
System.out.println("Random Uppercase Letter: " + randomUppercaseLetter);
}
}

40.
import java.util.Scanner;
public class IntegerCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int positiveCount = 0; // Counter for positive numbers


int negativeCount = 0; // Counter for negative numbers
int total = 0; // Accumulator for the sum of all numbers
int input; // Variable to store user input

System.out.println("Enter an int value, the program exits if the input is 0:");

do {
input = scanner.nextInt();

if (input > 0) {
positiveCount++; // Increment positiveCount if input is positive
} else if (input < 0) {
negativeCount++; // Increment negativeCount if input is negative
}
total += input; // Add input to the total sum
} while (input != 0);

double average = (double) total / (positiveCount + negativeCount); // Calculate the average

System.out.println("The number of positives is " + positiveCount);


System.out.println("The number of negatives is " + negativeCount);
System.out.println("The total is " + total);
System.out.println("The average is " + average);}}
41.
import java.util.Scanner;

public class FirstDaysOfMonth {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Prompt the user to enter the year and first day of the year
System.out.print("Enter the year: ");
int year = input.nextInt();
System.out.print("Enter the first day of the year (0 for Sunday, 1 for Monday,
etc.): ");
int firstDay = input.nextInt();

// Display the first day of each month in the year


String[] months = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

for (int i = 0; i < months.length; i++) {


System.out.println(months[i] + " 1, " + year + " is " +
getDayOfWeek(firstDay));
firstDay = (firstDay + daysInMonth[i]) % 7;
}
}

// Method to get the day of the week


public static String getDayOfWeek(int day) {
String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
return daysOfWeek[day];
}
}
42.
import java.util.Scanner;

public class DisplayCalendar {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Prompt the user to enter the year and first day of the year
System.out.print("Enter the year: ");
int year = input.nextInt();
System.out.print("Enter the first day of the year (0 for Sunday, 1 for Monday,
etc.): ");
int firstDay = input.nextInt();

// Display the calendar for each month in the year


String[] months = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

for (int i = 0; i < months.length; i++) {


System.out.println(months[i] + " " + year);
System.out.println("Sun Mon Tue Wed Thu Fri Sat");

// Print the leading spaces for the first day of the month
for (int j = 0; j < firstDay; j++) {
System.out.print(" ");
}

// Print the days of the month


for (int day = 1; day <= daysInMonth[i]; day++) {
System.out.printf("%3d ", day);
if ((day + firstDay) % 7 == 0 || day == daysInMonth[i]) {
System.out.println();
}
}

// Calculate the first day of the next month


firstDay = (firstDay + daysInMonth[i]) % 7;

System.out.println();
}
}
}
Array Exercise
43. a) One-dimensional array P contains four elements. The names of those elements are
____P[0]___, __P[1]____, ___P[2]___ and ___P[3]______.
b) Naming an array, stating its type and specifying the number of dimensions in the
array is called ___declaring______ array.
c) In a two-dimensional array, the first index identifies ___row_____ of an element and
the second index identifies the ___column_____ of an element.
d) An m-by-n array contains __m___ rows, ____n_____ columns and ___m*n____
elements.
e) The name of the element in row 3 and column 5 of array d is ____d[2][4]________.

44. a) False. To refer to a particular location or element within an array, we specify the
name of the array and the index of the particular element, not the value.
b) True.
c) False. To indicate that 100 locations should be reserved for an integer array p, you
write the declaration as int p[100];. The square brackets should be placed before the
array name to indicate the size of the array.
d) False. An application can initialize the elements of a 15-element array to zero
without using a for statement by utilizing array initialization syntax. For example, in
Java, you can declare and initialize an array with 15 elements all set to zero as follows:
e) True
45. a) To display the value of element 6 of array f,
=> System.out.println(f[5]); // Arrays are 0-indexed in Java, so the 6th element is at
index 5
b) To initialize each of the five elements of one-dimensional integer array g to 8
=> for (int i = 0; i < g.length; i++) {
g[i] = 8;
}
c) To total the 100 elements of floating-point array c:
=> double total = 0.0;
for (int i = 0; i < c.length; i++) {
total += c[i];
}
System.out.println("Total: " + total);
d) To copy 11-element array a into the first portion of array b, which contains 34
elements:
=> int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int[] b = new int[34];

for (int i = 0; i < a.length; i++) {


b[i] = a[i];
}
e) To determine and display the smallest and largest values contained in 99-element
floating-point array w:
=> double smallest = w[0];
double largest = w[0];
for (int i = 1; i < w.length; i++) {
if (w[i] < smallest) {
smallest = w[i];
}
if (w[i] > largest) {
largest = w[i];
}
}
System.out.println("Smallest: " + smallest);
System.out.println("Largest: " + largest);
46.
a) To declare and create a two-by-three integer array t in Java:
=> int[][] t = new int[2][3];
b) The array t has 2 rows.
c) The array t has 3 columns.
d) The array t has a total of 6 elements (2 rows * 3 columns).
e) Access expressions for all the elements in row 1 of t:
=> t[1][0], t[1][1], t[1][2]
f) Access expressions for all the elements in column 2 of t:
=> t[0][1], t[1][1]

g) Write a single statement that sets the element of t in row 0 and column 1 to zero:

=> t[0][1] = 0;

h) Write individual statements to initialize each element of t to zero:

t[0][0] = 0;

t[0][1] = 0;

t[0][2] = 0;

t[1][0] = 0;

t[1][1] = 0;

t[1][2] = 0;

i) Write a nested for statement that initializes each element of t to zero:

for (int i = 0; i < t.length; i++) {

for (int j = 0; j < t[i].length; j++) {

t[i][j] = 0;

}
j) Write a nested for statement that inputs the values for the elements of t from the user:

Scanner scanner = new Scanner(System.in);

for (int i = 0; i < t.length; i++) {

for (int j = 0; j < t[i].length; j++) {

System.out.print("Enter the value for t[" + i + "][" + j + "]: ");

t[i][j] = scanner.nextInt();

k) Write a series of statements that determines and displays the smallest value in t:

int smallest = t[0][0];

for (int i = 0; i < t.length; i++) {

for (int j = 0; j < t[i].length; j++) {

if (t[i][j] < smallest) {

smallest = t[i][j];

System.out.println("The smallest value in t is: " + smallest);


l) Write a single printf statement that displays the elements of the first row of t:

=> System.out.printf("%d %d %d%n", t[0][0], t[0][1], t[0][2]);

m) Write a statement that totals the elements of the third column of t. Do not use repetition:

=> int totalThirdColumn = t[0][2] + t[1][2];

n) Write a series of statements that displays the contents of t in tabular format. List the column
indices as headings across the top, and list the row indices at the left of each row:

System.out.println(" 0 1 2");

for (int i = 0; i < t.length; i++) {

System.out.print(i + " ");

for (int j = 0; j < t[i].length; j++) {

System.out.print(t[i][j] + " ");

System.out.println();

}
47.
import java.util.Scanner;
public class SalesCommissions {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] counters = new int[9]; // Array of counters for each salary range
System.out.print("Enter the number of salespeople: ");
int numSalespeople = scanner.nextInt();

for (int i = 0; i < numSalespeople; i++) {


System.out.print("Enter gross sales for salesperson " + (i + 1) + ": ");
double grossSales = scanner.nextDouble();
double salary = 200 + (0.09 * grossSales); // Calculate the salary
int range = (int) (salary / 100); // Determine the salary range
if (range < 2) {
counters[0]++;
} else if (range >= 10) {
counters[8]++;
} else {
counters[range - 1]++;
}
}
// Display the results
for (int i = 0; i < counters.length; i++) {
if (i == 0) {
System.out.printf("$%d-%d: %d%n", 200, 299, counters[i]);
} else if (i == 8) {
System.out.printf("$%d and over: %d%n", 1000, counters[i]);
} else {
System.out.printf("$%d-%d: %d%n", (i * 100) + 300, (i * 100) + 399,
counters[i]);}}}}}
Salary Range Number of Salespeople
$200 - $299 0
$300 - $399 0
$400 - $499 0
$500 - $599 0
$600 - $699 0
$700 - $799 0
$800 - $899 1
$900 - $999 0
$1000 and over 0

You might also like