Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write a function that multiplies each element in the array "myArray" by the variable "multiplyMe". c++

I’m supposed to use a function to multiply all elements of an array by 5 and print the numbers after. I don’t understand how to put the array in the function definition.

What i tried:

#include <iostream>

using namespace std;

// TODO - Write your function prototype here
int MultiplyArray(int[], int);

int main()
{
    const int SIZE = 10;
    int myArray[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
    int multiplyMe = 5;

    // TODO - Add your function call here
    MultiplyArray(myArray, multiplyMe);

    // print the array
    for(int i=0; i < SIZE; i++)
    {
        cout << myArray[i] << " ";
    }
    cout << endl;

    return 0;

}

// TODO - Write your function definition here
int MultiplyArray(int myArray[10], int m) {
  for (int i = 0; i <= 10; i++) {
    myArray[i] *= m;
    }
}

The output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 sh -c make -s
 ./main
signal: segmentation fault (core dumped)

Expected output:

25 50 75 100 125 150 175 200 225 250

>Solution :

You are very close. Simply remove the 10 from the [] in the function’s parameter type, and use < instead of <= in your function’s loop. Your loop is going out of bounds of the array (look at the loop in main(), it is using < correctly).

int MultiplyArray(int myArray[], int m) {
  for (int i = 0; i < 10; ++i) { // <--
    myArray[i] *= m;
  }
}

That being said, consider passing the array’s size as a parameter, too:

#include <iostream>

using namespace std;

// TODO - Write your function prototype here
int MultiplyArray(int[], int, int);

int main()
{
    const int SIZE = 10;
    int myArray[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
    int multiplyMe = 5;

    // TODO - Add your function call here
    MultiplyArray(myArray, SIZE, multiplyMe);

    // print the array
    for(int i = 0; i < SIZE; ++i)
    {
        cout << myArray[i] << " ";
    }
    cout << endl;

    return 0;

}

// TODO - Write your function definition here
int MultiplyArray(int myArray[], int size, int m) {
  for (int i = 0; i < size; ++i) {
    myArray[i] *= m;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading