Arrays programme won't give right answer.

// Can anyone please tell me that what is wrong with my programme? I'm trying to learn arrays. I understood the concept but this programme is not giving right answer. It always gives 6366923 as the final answer. What to do? :/


#include <iostream.h>
#include <conio.h>

int main()
{

int age[6];
int sum;
int count;
int avg;

for(count=0; count<6; count++)
{
cout<<"Enter the age of the student"<<count<<":";
cin>>age[count];

}

sum=0;
for(count=0; count<10; count++)
{

sum= sum+ age[count];

}

avg = sum/6;
cout<<"The average age of the class is ="<<avg;
getch();

}
Your second for loop tries to access data outside of the range of your "age[]" array. "age[]" is only 6 elements large but 'count' goes up to 10.
Your second for loop is count < 10, when it should be 6. Also I recommend having constant variables. Like this.
1
2
3
4
5
6
7
8
9
10
const int AMMOUNT = 6;
int age[AMMOUNT ];
for( int count = 0; count < AMMOUNT ; count++ )
{
    //cin stuff
}
for( int count = 0; count < AMMOUNT ; count++ )
{
    //+ sum stuff
}
closed account (iAk3T05o)
You put count< 6 in the first loop and count < 10 in the second for a array of [6]
Thanks everyone for replying. It worked. Such a silly mistake :)
Topic archived. No new replies allowed.