How do I make this for loop work

So I've been messing with this code for a while trying to insert an integer into a list with a function call. Here is the function call in the main file. This compiles but gives me a blank list and I can't figure out why.
//Function calls in main
print(aList, size);
insert(0, 10, aList, size);
insert(1, 20, aList, size);
insert(2, 25, aList, size);
insert(0, 4, aList, size);
insert(1, 40, aList, size);
print(aList, size);

#include "list.h"
#include <iostream>
using namespace std;

bool insert(int position, int val, int intList[], int& size)
{
int originalValue = intList[position];
if(originalValue == 0) {
intList[position] = val;
}
else {
for(int i = size - 1; i > position; i--) {
intList[i] = intList[i + 1];
}
intList[position] = val;
}
return true;
}

void print(const int intList[], int size)
{
cout << endl << "[ ";
for(int i=0; i<size; i++)
{
cout << intList[i] << " ";
}
cout << "]" << endl;
}
Maybe something like this.

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
#include <iostream>
using namespace std;

void insert(int pos, int val, int list[], int size) {
    if (list[pos] != 0)
        for (int i = size - 1; i > pos; i--)
            list[i] = list[i - 1];
    list[pos] = val;
}

void print(const int list[], int size) {
    cout << "\n[ ";
    for (int i = 0; i < size; i++)
        cout << list[i] << ' ';
    cout << "]\n";
}

int main() {
    const int Size = 10;
    int list[Size]{};
    print(list, Size);
    insert(0, 10, list, Size);
    insert(1, 20, list, Size);
    insert(2, 25, list, Size);
    insert(0,  4, list, Size);
    insert(1, 40, list, Size);
    print(list, Size);
}

Last edited on
Topic archived. No new replies allowed.