Write a program which can read a PGM into an array, then loop through the array
ID: 3674922 • Letter: W
Question
Write a program which can read a PGM into an array, then loop through the array to find the minimum value, maximum value, average value and median value. You do not need to print out or draw a histogram, but (see below) calculating the histogram can help you get the median. My results below show both a histogram table and a graphical histogram.
C++
Write a program to read an elevation map and write out a PGM which displays the elevations as a PGM, which the lowest pixels displayed as black and the highest elevations displayed as white. Use 255 as the PGM maxval, so the pixels at the lowest elevation should be output as 0 (black), pixels at the highest elevation as 255 (white), and all values in between scaling appropriately.
C++
Explanation / Answer
#include <iostream>
using namespace std;
//function to sort an array
void sort(float arr[], int n)
{
//pos_min is short for position of min
int pos_min;
float temp;
for (int i=0; i < n-1; i++)
{
pos_min = i;//set pos_min to the current index of array
for (int j=i+1; j < n; j++)
{
if (arr[j] < arr[pos_min])
pos_min=j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}
int main()
{
int n;
cout<<"How many PGM value want to read ? : ";
cin>>n;
float array[n];// array to store n PGM value
//reading n PGM value
cout<<"Enter "<<n<<" PGM value"<<endl;
for(int i=0; i<n; i++){
cin>>array[i];
}
// sorting array to find Min, Max and Median
sort(array, n);
float min = array[0];
float max = array[n-1];
float median;
if(n%2 == 0)// if length is even, average of two medille element is median
median = (array[n/2 -1 ]+ array[n/2])/2.0;
else
median = array[n/2];// if length id odd, only one element is median
cout<<"minimum: "<<min<<", maximum: "<<max<<", and median: "<<median<<endl;
return 0;
}
/*
Output:
How many PGM value want to read ? : 6
Enter 6 PGM value
12.32
10.2
16.3
20.0
19.9
9.99
minimum: 9.99, maximum: 20, and median: 14.31
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.