I wanted to make a function called fillArray to set up random values to the Array. Then i wanted the function to output all the values but i kept getting values way above 99.
This is what i have written so far:
#include <ctime>
#include <iostream>
using namespace std;
void fillArray(){
srand(time(NULL));
const unsigned int sizeOfArray = 10; // this sets the array to the constant size of 10
int numberArray[sizeOfArray]; //this sets the array to the size of 'sizeOfArray' which is 10
for(int i = 0; i < sizeOfArray; i++)
{
numberArray[i] = rand() % 100;
cout << numberArray[i] << endl;
}
}
int main (){
void fillArray(int a[10], int randNum);
cout << numberArray[0] << " , " << numberArray[1] << " , " << numberArray[2] << " , " << numberArray[3] << " , " << numberArray[4] << " , " << numberArray[5] << " , " << numberArray[6] << " , " << numberArray[7] << " , " << numberArray[8] << " , " << numberArray[9] << '\n';
}
I understand the name numberArray hasnt been declared in the main function but just wondered what to do.
So, your error is simple:
You have declared a function in the main
function like this:
int main()
{
void fillArray(int a[10], int random);
}
But it should have been
int main()
{
fillArray(int a[10], int random);
}
Which is calling the fillArray
function
Also there are a few other things that i would like to add,
instead of fillArray
taking nothing it should take an array like this
template<auto Size>
void fillArray(int (&arr)[Size])
{
// Implemenatation
}
and also, it should not take a random number the function can do that in the function body.
When you are printing your array, you should use a loop or a specialized function to do it like this:
template<auto Size>
auto PrintArray(int (&arr)[Size])
{
for(int i = 0; i < Size; i++)
{
std::cout << arr[i] << ", ";
}
std::cout << "\n";
}
So, your final code would be something like the following:
#include <ctime>
#include <iostream>
using namespace std;
template<auto Size>
void fillArray(int (&numberArray)[Size]){
srand(time(NULL));
for(int i = 0; i < Size; i++)
{
numberArray[i] = rand() % 100;
}
}
template<auto Size>
auto PrintArray(int (&arr)[Size])
{
for(int i = 0; i < Size; i++)
{
std::cout << arr[i] << ", ";
}
std::cout << "\n";
}
int main (){
int numberArray[10];
void fillArray<10>(numberArray);
PrintArray<10>(numberArray);
}