Following along with some C programming training, the instructor show us a solution to a lesson that will randomly generate array values and then construct them in a barchart. Focusing on the part that generates the random numbers, the instructor said to setup a function like the one at line 25. I noticed I could not see anything that srand was doing in the for loop. I then commented it out and get the same exact result when I compile. How or why is the srand function important?
Code:
//Function prototypes
void showBarChart(void);
void showOneBar(int barLength);
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 10
//Function prototypes
void showBarChart(void);
void showOneBar(int barLength);
void setDataValues(void);
int dataSet[DATA_SIZE];
int main(void) {
setDataValues();
showBarChart();
return EXIT_SUCCESS;
}
//---- FUNCTION DEFINITIONS ----
void setDataValues(void){
/*
* Generates a set of random data points between 0 and 49
* and populates the dataSet array
*/
srand(time(NULL));
for(int i=0; i<DATA_SIZE; i++){
dataSet[i] = rand() % 50; //random integers between 0 and 49
}
}
void showBarChart(void){
/*
* Loops through the dataSet array, reads each data point
* and calls the showOneBar function with that value
*/
for(int i=0; i<DATA_SIZE; i++){
showOneBar(dataSet[i]);
}
}