Name: CRN:_ CS 1113 : Homework 5-Working with arrays 1. Trace the following code
ID: 3585704 • Letter: N
Question
Name: CRN:_ CS 1113 : Homework 5-Working with arrays 1. Trace the following code by hand, writing what it prints? Do not compile and run it. Simulate it by hand tracing. intli anew int(51: intll b -a a15 I1 Your answer here for (int ili ica.length; i a[i]-a[1] + bi-1] + 1; System . out .printt("a [%d] d, b[%d]"%d ", 2. The code bel element to 20, but there is are a few errors in the code errors. Rewrite the code to fix the errors. ow is supposed to instantiate an array called b with 500 elements and set the value of each b int new 500 int ) for [int i 1. iExplanation / Answer
Answer 1)
a[1]=7, b[1]=7
a[2]=8, b[2]=8
a[3]=9, b[3]=9
a[4]=10, b[4]=10
Explanation:
int[] b=a; => This line would mean that b points to the same memory location as that of a. Any change made in a would be reflected in b, and vice versa.
So, b[1]+=1 => b[1]=b[1]+1 = a[1]+1=6
In loop's first iteration, a[1]=a[1]+b[0]+1
b[0] is currently not defined, so it would be 0 by default.
So, a[1]=6+0+1=7
and b[1]=a[1].
In second iteration, a[2]=a[2]+b[1]+1
=0 + 7 + 1 =8
and so on in further iterations...
Answer 2)
There were several errors in syntax, please find the correct on below:
int[] b=new int[500];
for(int i=0; i<b.length ; b++)
{
b[i]=20;
}
Answer 3)
public static String findMatch(String[] b, String[] c){
for(int i=0;i<b.length;i++){
for(int j=0;j<c.length;j++){
if(b[i].equals(c[j])){
return b[i];
}
}
}
return null;
}
Let me know if you have any doubts!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.