Write a program in Java to do the following: -Create a one-dimensional array of
ID: 3790571 • Letter: W
Question
Write a program in Java to do the following:
-Create a one-dimensional array of 7 integers as follows:
Assign {35,20,-43,-10,6,7,13}
-Create a one dimensional array of 7 Boolean values as follows:
Assign {true,false,false,true,false,true,false}
-Create a one dimensional array of 7 floating-point values as follows:
Assign {12.0f,1.5f,-3.5f,-2.54f,3.4f,45.34f,22.13f}
-Declare sum as integer and set it to 0.
-Declare sumf as float and set it to 0.0f.
-Use a for loop to go through each element of the Boolean array, and if an element is “true” then add the corresponding element in the integer array to sum, and also add the corresponding element in the floating-point array to sumf.
-Print all three arrays, sum, and sumf.
Explanation / Answer
TestArray.java
public class TestArray {
public static void main(String[] args) {
int[] ilist = {35,20,-43,-10,6,7,13};
Boolean[] array = {true,false,false,true,false,true,false};
float[] farray = {12.0f,1.5f,-3.5f,-2.54f,3.4f,45.34f,22.13f};
int sum=0;
float sumf=0.0f;
for (int i = 0; i < array.length; i++) {
System.out.print(ilist[i] + " ");
}
System.out.println();
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
for (int i = 0; i < array.length; i++) {
System.out.print(farray[i] + " ");
}
System.out.println();
for (int i = 0; i < array.length; i++) {
if(array[i]==true){
sum=sum+ilist[i];
sumf=sumf+farray[i];
}
}
System.out.println("sum = "+sum + " ");
System.out.println("sumf = "+sumf + " ");
}
}
Output:-
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.