adding elements into arrays

Hi, I am a beginner and I want to learn how to insert an element into an array

thanks!!
Which kind of array you're making, dynamic or static?
Last edited on
I'm making a 1D array and is this what it shuold be??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

int main()
{
    int nu;
    int num [7];
    int arra[6];
    cout <<"enter the numbers in your array (has to be 6(six)digets long)"<<endl;
    for(int t=0;t<6; t++)
    {
    cout<<t<<endl;
      cin>>arra[t];
    }
    cout<<"what number do you want to insert:";
    cin>>nu;
    cout<<""<<endl;
    for(int t=0;t<6; t++)
    {
      cout<<arra[t]<<", ";
    }
    cout<<""<<endl;

    num[0]=arra[0];
    num[1]=nu;
    num[2]=arra[1];
    num[3]=arra[2];
    num[4]=arra[3];
    num[5]=arra[4];
    num[6]=arra[5];
    for(int o=0; o<7;o++)
    {
        cout<<num[o]<<", ";
    }
    return 0;
}
The problem with your code is that it always inserts at num[1]. That's fine if you don't care about the ordering of your numbers. If you don't care about the ordering, it's generally easier to copy the array and add to the end of the new array.

You might want to look into vectors. Vectors will resize automatically as you add elements.
http://www.cplusplus.com/reference/vector/vector/
Topic archived. No new replies allowed.