In: Computer Science
Rewrite your program for part 1. Do not declare the array globally, declare it in the loop function. This now requires that you add two parameters to your fill array and print array functions. You must now pass the array name and array size as arguments, when the program calls these functions. The program has the same behavior as problem 1, but illustrates the difference between globally and locally declared variables.
The program code for part 1 was:
int Array[15] = {0}; //declaration of global array size 15
void setup(){
Serial.begin(9600); //start with baud rate of 9600
}
void loop(){
fillArray(10,99); //fills array with random numbers between 1 and
99
delay(500);
printArray(5); //displays data with 5 numbers per line
delay(1000); //prints data on serial monitor every second
}
void fillArray(int low, int high){
for(int i = 0; i < (sizeof(Array)/sizeof(Array[0])); i++){
//size of array
Array[i] = random(low,high);
}
}
void printArray(int NumberPerLine){
Serial.println("Array is:"); //prints the text and adds new
line
int counter = 0; //variable to store how many numbers printed
for(int i = 0; i < (sizeof(Array)/sizeof(Array[0])); i++){
if(counter == NumberPerLine){
Serial.println(""); //print new line
counter = 1; //number printed on a single line is again set to
1
}
else{
counter++; //adds 1 to counter
}
Serial.print(Array[i]); // print numbers one by one
Serial.print(" "); //adds space between each number
}
Serial.println(""); //adds new line
}
Updated Code
//declaration of global array size 15
void setup()
{
Serial.begin(9600); //start with baud rate of 9600
}
void loop()
{
const int arraySize = 15;
int Array[arraySize] = {0};
fillArray(10,99,Array,arraySize); //fills array with random numbers
between 1 and 99
delay(500);
printArray(5,Array,arraySize); //displays data with 5 numbers per
line
delay(1000); //prints data on serial monitor every second
}
void fillArray(int low, int high,int Array[],int
arraySize)
{
for(int i = 0; i < arraySize; i++){ //size of array
Array[i] = random(low,high);
}
}
void printArray(int NumberPerLine,int Array[],int
arraySize)
{
Serial.println("Array is:"); //prints the text and adds new
line
int counter = 0; //variable to store how many numbers printed
for(int i = 0; i < arraySize; i++){
if(counter == NumberPerLine)
{
Serial.println(""); //print new line
counter = 1; //number printed on a single line is again set to
1
}
else{
counter++; //adds 1 to counter
}
Serial.print(Array[i]); // print numbers one by one
Serial.print(" "); //adds space between each number
}
Serial.println(""); //adds new line
}
output
If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.