How to calculate the arithmetic average of the elements of a vector with c plus plus
In this simple example, it shows how to calculate the arithmetic average of the elements of a vector. This example is useful for understanding how to generate random integers and how to use the array.
#include <iostream>
int main (int argc, char *argv[])
{
// Initialize random number generator
srand(time(NULL));
// Define the length of the array
const int LENGHT = 10;
// Create an array of LENGTH elements
int v[LENGHT];
// Fill the array with random integers
for (int i=0; i<LENGHT; i++) v[i] = (rand()%100)+1;
// Showing the contents of the array
printf("The contents of the array\n");
for (int i=0; i<LENGHT; i++) printf("%d\t" , v[i]);
// Calculating the arithmetic average of the values contained in the array
double average = 0.0;
for (int i=0; i<LENGHT; i++) average+=v[i];
average = average/LENGHT;
printf("\n\n");
printf("The arithmetic average is: %f" , average);
return 0;
}
This is the result:
The contents of the array
44 93 45 72 77 41 5 50 80 64
The arithmetic average is: 57.100000