Integer Insertion - User Input

Integer Insertion - User input

Make a program with an int array of size 0. The user is prompted to add a starting number, which is placed in the array. You can use std::vector::push_back for this.

After this, the user is prompted to add a number and specify where he wants to place the number. Use std::vector::insert for placement. If the user asks to add a number outside of the array range, he is told that the locatation doesn't exist, but that his number was added to the start/end of the array.

The full array should be output each time a number is added.

Answer

#include <iostream>
#include <vector>

void printArray(std::vector<int> numbers) {
    std::cout << "Current array: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}

int main() {
    std::vector<int> numbers;
    int startingNumber;

    // Prompt for the starting number
    std::cout << "Enter a starting number: ";
    std::cin >> startingNumber;
    numbers.push_back(startingNumber);

    while (true)
    {
        // Display the current array
        printArray(numbers);

        int number, position;

        // Prompt for a new number and its desired position
        std::cout << "Enter a number to insert: ";
        std::cin >> number;
        std::cout << "Enter position to insert the number at: ";
        std::cin >> position;

        // Check if the position is valid
        if (position >= 0 && position <= numbers.size())
        {
            // Insert normally if the position is valid
            numbers.insert(numbers.begin() + position, number);
        }
        // Check if the position is invalid because it's too small
        else if (position < 0)
        {
            // Insert at the start of the array
            std::cout << "Location doesn't exist. Adding to the start of the array." << std::endl;
            numbers.insert(numbers.begin(), number);
        }
        // Else , the position is invalid because it's too large
        else
        {
            // Insert at the end of the array
            std::cout << "Location doesn't exist. Adding to the end of the array." << std::endl;
            numbers.push_back(number);
        }
    }
}

We don't have to call printArray at the end of the loop because we are using an infinite loop. We don't need to worry about making sure we print the final value before the program exits, because it isn't going to exit. Putting the printArray call at the start of the loop makes it print the array when it only has 1 element (after the users first input).

If the code reaches the last else statement, we already know that position has to be above numbers.size().

It can't be between or including 0 and numbers.size(). The first if statement would be true. Hence, further else checks would never occur.

It can't be below 0. The else if statement would be true. Hence the else statement wouldn't have been reached.

Questions