Question

complete in C++ code Lists Many programming languages have some kind list data structure, which allows...

complete in C++ code

Lists

Many programming languages have some kind list data structure, which allows for insertion and deletion of elements, essentially an array that changes size. C++ has vectors, Java has the ArrayList, Python has lists (which is what they're called generically anyway). But how do they really work? All of these actually use arrays, which naturally have immutable lengths.

Your Task

Your task is to write a function, insert, which inserts a new item into an existing array, then returns the modified array. Since you can not really do this, you will have create a new array which has all the elements of the original array, plus the new item in its proper place, and return that new array instead. This is how lists actually work. I won't make you write the code for deleting items; after you do this, you'll understand how it works anyway.

You may notice that the return type of insert is a pointer to an integer. This is fine, since an array is just a pointer to the first item in the array.

Grading

2 points for each:

  • Adds the new item to the array

  • Inserts the new item in the correct place

  • Does not remove any items from the array

  • Does not cause any memory leaks, segmentation faults, etc

  • Comments explains how it works




    The starter code is listed bellow

    #include <iostream> /* * insert takes an array of ints and inserts an item * at a given index, shifting all elements to the right * to make room for it as needed. There must be a * length number of integers in the array. It then * returns the new array with item inserted correctly. * * If index >= length, item is appended to the array * If index < 0, insertion point is calculated counting * from the end of the array. -1 = length-1, etc. */ int * insert(int arr[], int length, int item, int index); /* * print takes an array of ints and prints it * with spaces between each item. There must be * a length number of integers. */ void print(int arr[], int length); int main() { //These next two lines make an array and put numbers in it int * numbers = new (std::nothrow) int [4]; for(int i = 0; i < 4; i++) { numbers[i] = (i * 2) + 2; } //Prints 2 4 6 8 print(numbers, 4); numbers = insert(numbers, 4, 100, 2); //Prints 2 4 100 6 8 print(numbers, 5); //Feel free to add your own test cases here, // to make sure your function works //Memory cleanup delete [] numbers; return 0; } int * insert(int arr[], int length, int item, int index) { //YOUR CODE GOES HERE return arr; //Delete this line } void print(int arr[], int length) { for(int i = 0; i < length; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program:

#include <iostream>
/* * insert takes an array of ints and inserts an item
* at a given index, shifting all elements to the right
* to make room for it as needed. There must be a
* length number of integers in the array. It then
* returns the new array with item inserted correctly.
* If index >= length, item is appended to the array
* If index < 0, insertion point is calculated counting
* from the end of the array. -1 = length-1, etc. */

int * insert(int arr[], int length, int item, int index);

/* * print takes an array of ints and prints it
* with spaces between each item. There must be
* a length number of integers. */

void print(int arr[], int length);

int main()
{
//These next two lines make an array and put numbers in it
int * numbers = new (std::nothrow) int [4];

for(int i = 0; i < 4; i++)
{
numbers[i] = (i * 2) + 2;
}

//Prints 2 4 6 8
print(numbers, 4);
numbers = insert(numbers, 4, 100, 2);
//Prints 2 4 100 6 8
print(numbers, 5);
//Feel free to add your own test cases here,
// to make sure your function works
//Memory cleanup
delete [] numbers;

return 0;
}

int * insert(int arr[], int length, int item, int index)
{
//create a new array
int *numbers = new (std::nothrow) int [length + 1];

//copy all the elements of the original array
for(int i = 0; i < length; i++)
{
numbers[i] = arr[i];
}

if(index < 0) index = length + index;

//shifting all elements to the right
for(int i=length; i>=index; i--)
{
numbers[i] = numbers[i-1];
}

//insert new item in its proper place
numbers[index] = item;

//Memory cleanup
delete [] arr;

//return the new array
return numbers;
}

void print(int arr[], int length)
{
for(int i = 0; i < length; i++)
{
std::cout << arr[i] << " ";
}

std::cout << std::endl;
}

Output:

N.B. Whether you face any problem then share with me in the comment section, I'll happy to help you.

Add a comment
Know the answer?
Add Answer to:
complete in C++ code Lists Many programming languages have some kind list data structure, which allows...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The following code is a Java code for insertion sort. I would like this code to...

    The following code is a Java code for insertion sort. I would like this code to be modified by not allowing more than 10 numbers of integer elements (if the user enters 11 or a higher number, an error should appear) and also finding the range of the elements after sorting. /* * Java Program to Implement Insertion Sort */ import java.util.Scanner; /* Class InsertionSort */ public class InsertionSortTwo { /* Insertion Sort function */ public static void sort( int...

  • Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong...

    Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong here is what i was told that was needed. Ill provide my code at the very end. Here is what is missing : Here is my code: public class GSL { private String arr[]; private int size; public GSL() {     arr = new String[10];     size = 0; } public int size() {     return size; } public void add(String value) {    ...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

  • Using C programming

    Using C, create a data file with the first number being an integer. The value of that integer will be the number of further integers which follow it in the file. Write the code to read the first number into the integer variable how_many.Please help me with the file :((This comes from this question:Write the code to dynamically allocate ONE integer variable using calloc (contiguous allocation) or malloc (memory allocation) and have it pointed to by a pointer (of type int...

  • IN C Programming #include<stdio.h> #include<stdlib.h> typedef struct nodestruct { int item; struct nodestruct *next; } Node;...

    IN C Programming #include<stdio.h> #include<stdlib.h> typedef struct nodestruct { int item; struct nodestruct *next; } Node; typedef struct { int size; // Number of items on user’s list Node *head, *tail; } List; //In addition to creating an empty list, this function will also create two dummy nodes; one for the head, and the other for the tail. List* createList(); //This function creates a node containing the provided item, then inserts it into the list pointed by the provided list...

  • using c++ 13 do pretty much whatever they want Exercise: Array Resizing You will create an...

    using c++ 13 do pretty much whatever they want Exercise: Array Resizing You will create an array manipulation program that allows the user is to pre much whatever meant to ananas Wananching the program the user will passat are the contains a set of value and that w 2 Check to see the could be opened at the program was not opened the continue 3. Create an array and with the values from Presente en de h and powermany reded...

  • I’m giving you code for a Class called GenericArray, which is an array that takes a...

    I’m giving you code for a Class called GenericArray, which is an array that takes a generic object type. As usual this is a C# program, make a new console application, and for now you can stick all of this in one big file. And a program that will do some basic stuff with it Generic Array List What I want you to do today: Create methods for the GenericArray, Easy(ish): public void Append (T, value) { // this should...

  • a Java code Complete the provided code by adding a method named sum() to the LinkedList...

    a Java code Complete the provided code by adding a method named sum() to the LinkedList class. The sum() method should calculate the sum of all of the positive numbers stored in the linked list. The input format is the number of items in the list, followed by each of the items, all separated by spaces. Construction of the linked list is provided in the template below. The output should print the sum of the positive values in the list....

  • Must be written in C 89 Mode Array Insertion Your task is to complete the implementation...

    Must be written in C 89 Mode Array Insertion Your task is to complete the implementation of the insertion function, insert_into_array: int* insert_into_array(int arr[], size_t arr_len, int value, size_t pos); The insertion function inserts a value into an array at a specified position. All elements to the right of the inserted element are shifted over a position (upon inserting, all elements at the insertion position are shifted up an index, and the last element in the array is overwritten by...

  • pls help, idk whats wrong with this Add the reverse() method which reverses the content of...

    pls help, idk whats wrong with this Add the reverse() method which reverses the content of array without using additional array and the rotate(k) method which rotates left the content of array without using additional array by k elements. import java.util.*; * Implementation of the ADT List using a fixed-length array. * * if insert is successful returns 1, otherwise 0; * for successful insertion: * list should not be full and p should be valid. * * if delete...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT