The problem I have is that the variable always returns 0 for the lowest number and I can't see any problem as the highest numbers returns the correct value. Code as follows.Help would be highly appreciated, thanks.
#include <iostream>
#include <string>
usingnamespace std;
int mark[20];
int count;
int highest = mark[0];
int lowest = mark[0];
int sum = 0;
int main()
{
do
{
count++;
cout << "Enter mark " << count << endl;
cin >> mark[count];
}
while (count < 20);
for(int i=1;i<=20;i++)
{
if (highest < mark[i])
highest=mark[i];
}
cout << "The highest number is " << highest << endl;
for(int x=1;x<=20;x++)
{
if (lowest > mark[x])
lowest=mark[x];
}
cout << "The lowest number is " << lowest << endl; //lowest always returns 0 for some reason?
for(int i=1;i<=20;i++)
{
sum+=mark[i];
}
cout << "The average grade is " << sum / 20 << endl << endl;;
cout << mark[0];
cin >> sum;
}
Lim Boon Jye is correct about the loop iteration. C++ arrays are zero based so the first memory spot in your array is mark[0] When you use the for loop that you are using:
for ( int i = 1; i <= 20; i++ )
you are leaving mark[0] set to zero and entering data in the next 20 memory blocks starting at mark[1]
memory slot 1 --------> mark[0]
memory slot 2 --------> mark[1] <----- You are starting here
memory slot 3 --------> mark[2]
memory slot 4 --------> mark[3]
memory slot 5 --------> mark[4]
if you use this loop:
for ( int i = 0; i < 20; i++ )
you will be starting at mark[0] and the value (0) that is in that memory slot will be over written by the grade that is entered. That way the lowest value in your mark[] array will not be zero unless zero is entered as a mark.
Although BOTH of these loops count 20 spots
for ( int i = 1; i <= 20; i++ )
for ( int i = 0; i < 20; i++ )