Need help with shifting all values to the left of an array and place a 0 in the last location each time it is called.?
Create a new Java program called LeftShift.
Create an array size 10 that contains 1’s and 0’s only. (Any combination.)
Create a method called shiftValues that passes an array. It should shift all values to the left and place a 0 in the last location each time it is called.
Call your shiftValues method a three times to show shift.
Paste code here once completed.
NOTE: To earn the extra credit, program must show use of the pass by reference concept, which means you should only have one array throughout the entire program.
import java.util.*;
public class LeftShift{
static Random r=new Random();
public static final int dice=2;
public static final int size=10;
public static final int count=5;
public static void main(String[] args){
int[] a=new int[size];
for(int i=0;i<size;i++){
int seq=r.nextInt(dice);
a[i]=seq;
}
System.out.println("Sequence: "+Arrays.toString(a));
for(int i=0;i<count;i++){
shiftValues(a);
}
}
public static void shiftValues(int[] a){
for(int i=0;i<a.length-1;i++){
a[i]=a[i+1];
a[a.length-1]=0;
}
System.out.println("Sequence: "+Arrays.toString(a));
}
}
Answers
brilliant_moves
Hi, kupokupo. Your code is nearly right, but I've had to make some changes.
import java.util.*;
public class LeftShift{
... static Random r=new Random();
... public static final int dice=2;
... public static final int size=10;
... public static final int count=3;
... public static void main(String[] args){
... ... int[] a=new int[size];
... ... for(int i=0;i<size;i++){
... ... ... int seq=r.nextInt(dice);
... ... ... a[i]=seq;
... ... }
... ... System.out.println("Sequence: "+Arrays.toString(a));
... ... for(int i=0;i<count;i++){
... ... ... System.out.println ("Sequence: "+Arrays.toString (shiftValues(a)));
... ... }
... }
... public static int[] shiftValues(int[] a){
... ... for(int i=0;i<a.length-1;i++){
... ... ... a[i]=a[i+1];
... ... }
... ... a[a.length-1]=0;
... ... return a;
... }
}
//Note: To show indentation (which Y!A removes), I've used "... ". Replace dots with a tab or spaces in your code.
Was this article helpful?
Thank you! Your feedback will help us improve the support experience.
Related questions
Question about Assembly Language. What is this line doing?
Given the MASM data declarations below.
.DATA
OddArray word 18,20,22,24
EvenArray word 19,21,23,25
1) Write the assembly language instructions to swap the values of the two arr...