Lowest value of array always shows 0

Apr 15, 2013 at 8:58am
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
using namespace 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;
}
Apr 15, 2013 at 9:06am
change your <= to <
should be okay

see your int array
maximum only[19]
but you compar euntil [20]
of course it's return 0
Last edited on Apr 15, 2013 at 9:07am
Apr 15, 2013 at 9:13am
Your problem is here:

int highest = mark[0];
int lowest = mark[0];

I changed it to this:

int highest = 0;
int lowest = 1000;

And it worked fine

mark[0] = 0. so you have declared:

int lowest = 0;
Last edited on Apr 15, 2013 at 9:16am
Apr 15, 2013 at 9:42am
sorry just see it.
no @brian

just put your count ++ after your cin

1
2
cin >> ..
count++;

and please change the sign as i stated just now
Apr 15, 2013 at 10:41am
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++ )

they do not count the SAME 20 spots.

Hope this helps you. :]
Topic archived. No new replies allowed.