Test ll Spring 2017 Programming Name: Ibra hee CSCI-125 MOS Prof. F, Fischman 1.
ID: 3831641 • Letter: T
Question
Test ll Spring 2017 Programming Name: Ibra hee CSCI-125 MOS Prof. F, Fischman 1. Consider the method doTask defined below. public static int doTask (intlla)( int soFare1: int count forint k-1: kca length; k When the following code segment is executed. int arreu, 2, 3, 3, 3, 3,4,2.2. 2. 2. 2.2.2, 5.66, 6.6 6.64, 7.8k System out printin(doTasklaml; what is printed to the screen? Why? 2. Assume that the following declarations have been made. intU A N1, 2, 3, 4, 5, 6 7,8l Also, assume that the method printcontents is defined with the following header and works as s llPrints the contents of array arr to the screen. public static void printcontents(int0 arr)Explanation / Answer
public static int doTask(int[] a)
{
int index = 0;
int soFar = 1;
int count = 1;
for(int k = 1; k < a.length; k++) //Starting from second value in the array.
{
if(a[k] == a[k-1]) //If the current value is same as the previous value.
{
count++; //Increment the count.
if(count > soFar) //If count is greater than soFar.
{
soFar = count; //Update soFar.
index = k; //Update index to current index.
}
}
else //If the current value is not same as previous value.
{
count = 1; //Reassign count again to 1.
}
}
return a[index]; //Print the value at index.
}
So, it will print the one with the longest run. So, in the given array, 2 is the one with the longest run. So, 2 is the output of that method with specified values.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.