Complete the project InsertlnOrder so that the user can enter positive integers
ID: 3832490 • Letter: C
Question
Complete the project InsertlnOrder so that the user can enter positive integers to be stored in ascending order in an array of capacity S. The project already contain code to declare an array and insert the first number. Once the first number is inserted a while loop start to iterate until the array a full. The loop will insert the elements in the array and print the array after each insertion. Once the array is full, a message will be displayed to end the program. Your job is to complete the while loop. Pseudocode: Ask the user which number to insert and store the number in a variable. If the number to insert is larger than the last number in the array Insert the number at the end of the array and increment the number of elements. ELSE //start traversing the array to find where to inert the number WHILE the location is not found and the end of the array has not been reached IF the number to insert is smaller or equal the element at this index Use a FOR loop to shift elements Insert the element Increment number of elements ELSE Move forward How do you insert an element in the array? You shift elements to the left to "make space" for the new number Example: If you want to insert 34, you should insert it at index 2. Starting from the end of the list, shift each element to its right. Overwrite element at index 2 with element to insert. Test your program by inserting: A number smaller than the first element A number larger than the last dement A number in between the first and last element A number already in the arrayExplanation / Answer
If a[] is the declared array and inserted with the first element then below is the code to implement the while loop required.
int count=1;
Scanner scanner = new Scanner(System.in);
while(count < a.length)
{
System.out.println("enter the number to insert");
int num = scanner.nextInt();
if(num >= a[count-1])
a[count++]=num;
else
{
int i=0;
while(i<count && num > a[i])
i++;
for(int j=count; j>i; j--)
a[j]=a[j-1];
a[i]=num;
count++;
}
for(int k=0; k<count; k++)
System.out.print(a[k]+" ");
System.out.println();
}
System.out.println("The Array got full");
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.