Calculate the maximum value and the minimum value among the items in an array with c plus plus
In some cases one needs to calculate the maximum and minimum of a range of integers, this simple example written in C++, shows how to do it.
#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 " , v[i]);
// Calculating the max value contained in the array
int max = v[0];
for (int i=1; i<LENGHT; i++)
if(v[i]>max) max = v[i];
// Calculating the min value contained in the array
int min = max;
for (int i=1; i<LENGHT; i++)
if(v[i]<min) min = v[i];
printf("\n\n");
printf("The max value is: %d\n" , max);
printf("The min value is: %d\n" , min);
return 0;
}
This is the result:
The contents of the array
31 41 49 12 30 47 24 33 52 4
The max value is: 52
The min value is: 4