JAVA Practice Problems -Arrays Using the scenario below, answer the following qu
ID: 666945 • Letter: J
Question
JAVA Practice Problems -Arrays
Using the scenario below, answer the following questions:
You are preparing for the Boston Marathon. In order to prepare, you need to train for 10 weeks, running an increasing number of miles per week, starting at running at least 2 miles your first week up to 26 miles by week 10.
1.) Initialize the array with the appropriate number of values.
2.) What is the value in the array element when the index contains 2?
3.) What is your list length?
4.) Calculate the sum of the total miles you spent running over the 10 weeks. Calculate the average number of miles you ran.
5.) Write a search to determine whether 4 is on your list
Explanation / Answer
Let assume that the miles for each week are in Arithmetic Progression. so increasing in miles from each week to next week is constant which can be determined using
an = a1+ (n-1)*d
where an is miles he run in 10th week.
a1 is mile he run in 1st week.
n is total number of weeks
d is constant that is the value by which he increase miles running in next week.
26 = 2 + 9*d
d = 24/9;
= 2.66 miles.
Question 1)
class first{
public static void main(String[] args){
double l = new double[10];
// miles for 1st week
l[0] = 2;
double diff = 2.66;
for (int i = 1; i < 10; i++){
l[i] = l[i-1] + diff;
}
}
}
Question 2)
l[2] = 2+2.66+2.66
= 7.32 miles
Question 3)
List length is 10;
Question 4)
class first{
public static double Sum(int[] l){
double sum = 0;
for (int i = 0; i < 10; i++){
sum += l[i];
}
return sum;
}
public static double Avg(double val, double len){
return val/len;
}
public static void main(String[] args){
double l = new double[10];
// miles for 1st week
l[0] = 2;
double diff = 2.66;
for (int i = 1; i < 10; i++){
l[i] = l[i-1] + diff;
}
// Sum
double res = Sum(l);
// Average
double ans = Avg(res,l.length);
}
}
Question 5)
class first{
public static void search(int[] l,int val){
for (int i = 0; i < l.length; i++){
if (l[i] == val)
return true;
}
return false;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.