Return to Topic Menu
|
Computer Science Main Page |
MathBits.com
|
Terms of Use
|
Resource CD
Demo Program -
Find Max/Min Value in an Array |
Task: Find the highest (maximum) and lowest (minimum) grades in an
array of 25 integer grades. Print the array and print the highest and
lowest grades,
labeled appropriately.
|
#include <iostream.h>
#include <apvector.h>
#include "apstring.cpp"
#include <stdlib.h>
#include <iomanip.h>
void fill(apvector <int>&grades);
int maxGrade(apvector <int>&grades);
int minGrade(apvector <int>&grades);
void print_It(apvector <int>&grades);
int main(void)
{
system ("CLS");
apvector <int> grades(25);
//Call function to fill the
array
fill(grades);
//Call function to print the
array
print_It(grades);
//Call function to find max
int maximum = maxGrade(grades);
//Call function to find min
int minimum = minGrade(grades);
cout<< "The highest grade in the array is
"<<maximum<<".\n";
cout<< "The lowest grade in the array is
"<<minimum<<".\n";
cout<<endl<<endl;
return 0;
}
//Function to fill array
void fill(apvector <int>&grades)
{
int len=grades.length( );
for(int i = 0; i < len; i++)
{
cout<<"Enter
grade: ";
cin>>grades[i];
}
return;
}
//Function to print array
void print_It(apvector <int>&grades)
{
int len=grades.length( );
for(int i = 0; i < len; i++)
{
if (i % 5 == 0)
//print a new line after every 5 values
cout<<"\n";
cout<<setw(4)<<grades[i];
//print values in 4 spaces
}
cout<<endl<<endl;
return;
}
//Function to find maximum
int maxGrade(apvector<int> &grades)
{
int length = grades.length( );
int maximum = grades[0];
for(int i = 1; i<length; i++)
{
if(grades[i] > maximum)
maximum = grades[i];
}
return maximum;
}
//Function to find minimum
int minGrade(apvector<int> &grades)
{
int length = grades.length( );
int minimum = grades[0];
for(int i = 1; i<length; i++)
{
if(grades[i] < minimum)
minimum = grades[i];
}
return minimum;
}
|
|
|