Categories

Tools

bitdefender

1&1 Web Hosting

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

Posted in C++ by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.