Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Put number in array C++

0 votes
asked Nov 30, 2017 by Gathern
I need to put in array a number entered by user with using -for,-while,-dowhile.

1 Answer

0 votes
answered Dec 3, 2017 by Luna
edited Dec 3, 2017
//Should i have used all the 3 loops? lol(?)

//and yeah i know, there is more elegant solutions for this out there, anyway i hope it helps

#include <iostream>

using std::cin;
using std::cout;

//This functions receives an array of int, it's size, the position to insert an element, and the element, and returns a new array.

int *addTo(int nArrA[], const int SIZE, int nPos, int nNumber)
    //creates a new array with one more position
    int *nArrB = new int[SIZE+1];
    //saves the value in that position
    int nValue = nArrA[nPos];
    for(int i = 0; i < SIZE; i++)
        if(i == nPos)
            nArrB[i] = nNumber;
            nArrB[i+1] = nValue;
        else if(i > nPos)
            nArrB[i+1] = nArrA[i];
            nArrB[i] = nArrA[i];
    return nArrB;

int main()

    //Create and array
    int nArray[7] = {0, 1, 2, 3, 4, 7, 12};

   //this will get the array's size
    int size = (sizeof(nArray)/sizeof(nArray[0]));
    int nValue = 0, nPos = 0;
    cout << "Type the value to insert in the array:\n";
    cin >> nValue;

    //Please do not explode the program, use some valid position.
    cout << "Type the position to insert the element:\n";
    cin >> nPos;
    int *arr = addTo(nArray, size, nPos, nValue);
    for(int i = 0; i <= 7; i++)
        cout << *(arr + i) << " ";

btw, sorry for my broken english
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.