passing array to a function

Hello,

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

int main()
{

        int array1[3] = {2,3,6};

        for (int i=0; i<3; ++i)
        {
                std::cout << "array1[" << i << "]=" << array1 << std::endl;
                getarray2 = (array1);
                std::cout << "array2[" << i << "]=" << array2 << std::endl;
        }

        return 0;
}

double getarray2 (int array1)
{
        static const float array1_To_array2[3] = {10.5,3.,30.5}
        return array1_To_array2[array1];
}


I have three elements in array1 and array2. I would like to get the element of array2 for a given element of array1. So, I would like to see an output like below. However, I am not sure how should I pass an array to a function ...



array1[0]=2
array2[0]=10.5
array1[1]=3
array2[1]=3.
array1[2]=6
array2[2]=30.5



Thanks for the help.

hope this helps
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
#include <iostream>
using namespace std; //with this you no longer need std's lol
void function(int array[]); // declare function outside of main.
int main()
{
     int array[3] = {2,3,6}; //array before function
    for (int i=0; i<3; ++i)
        {
              cout << array[i] << endl;
        }
        cout << "do something to the array" << endl;
    function(array); //call the function
    //show array after function
    for (int i=0; i<3; ++i)
        {
              cout << array[i] << endl;
        }
    system("PAUSE");
    return 0;
}
void function(int array[])
{
     //do something
     for (int i=0; i<3; ++i)
        {
              array[i] = 10+i;
        }    
}
smelas, I hope this helps, this is how I learned how to pass arrays into functions from thenewboston. You should check that site out, it goes pretty good with the lessons offered on cplusplus.com :) good way to get a different teacher's perspective.

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
//Thenewboston.com C++ Video Lesson 35 - Passing Arrays To Functions
#include <iostream>
using namespace std;

void printArray(int theArray[], int arraySize);

int main()
{
    int array1[5] = {5,4,3,2,1};
    int array2[6] = {6,5,4,3,2,1};

    printArray(array2, 6);
    //tell it the identifier of the array ONLY, and the size you pass as an argument.
    //this replaces the variables theArray and arraySize in the printArray function.
    return 0;
}

void printArray(int theArray[], int arraySize) 
//the variables theArray hold the array, arraySize holds size of array
{

    for(int x = 0;x<arraySize;x++)
//use a for loop to count the array element starting at 0 always.
        {
            cout << theArray[x] << endl;
//each time this loop runs through, it will up the value of x and print out the
//corresponding element of the array.
        }
}
Topic archived. No new replies allowed.