如何使用参数int n
声明数组的范围。
例如,如果n = 5
,我希望我的数组等于5索引。但是,就像您在我的主要内容中看到的那样,我有点手动对其进行了初始化。我只是不想在主要方面这样做。我只想声明n为5或10或其他任何值。
我知道这是一个简单的代码,但是我真的很想知道如何将数组作为参数传递而无需“手动”或像在主函数中那样。
#include <iostream>
using namespace std;
void printArray(int arr[], int n){
// please do not change above this line
/* Instruction 1: You will write a loop to print the content of the array arr passed into this function.
// There should be only one space after each integer you print and there must be only one newline
// at the end of printing all the numbers. n being the number of elements in arr
// So, just for example: if arr contains [10, 20, 30, 40, 50] then n = 5 and your loop should print
// 10 20 30 40 50
// There should be a newline at the end of the above line when printed.
*/ Write your code below reading the instruction above
for (int i = 0; i < n; ++i)
{
cout << arr[i] << " ";
}
cout << endl;
}
// Initialised the arr with 5 here but i want n to be the range of
//my array
int main()
{
int arr[5] = {1,2,3,4,5} ;
printArray(arr, 5);
}