Printing an array

Code is only returning 1. Not sure why, would really appreciate any help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int printArr(int arr[], int num);

int main()
{
    int arrOne[10] = {1,2,3,4,5,6,7,8,9,10};
    cout << printArr(arrOne, 10);

    return 0;
}

int printArr(int arr[], int num)
{
    for(int i=0; i<num; i++)
    {
        return arr[i];
    }

}
Well, it's doing exactly what you told it to. When you return something, the function returns to the caller, i.e. it's over. Doesn't matter that you're inside a loop. You returned the first element of the array, arr[0], from the function. Then, you printed that return value.

If you want to print an array, I suggest doing something like:

1
2
3
4
5
6
7
8
void printArr(int arr[], int num)
{
    for (int i = 0; i < num; i++)
    {
        cout << arr[i] << ' ';
    }
    cout << '\n';
}


Note that the function can be void, since you don't need to return anything; you're just printing.
Last edited on
Awesome! Thanks for the help.
Topic archived. No new replies allowed.