Hey everyone, I need help with this program I am writing which declares an array to hold 10 integers, and then find the sum of all the numbers in the array and also print out the average. Here is what I have so far:
#include <iostream>
using namespace std;
const int N=10;
int main ()
{
int num [10],i,sum,avg;
for (int i= 0; i<10; i++)
{
cout <<"Please enter a integer"<<endl;
cin>> num[i];
}
for (int i= 0; i<10; i++)
sum=sum +num[i];
cout <<"sum of array is"<<sum<<endl;
system ("pause");
return 0;
}
It keeps telling me that i, sum, and avg are not initialized and I don't understand why. Also, it is not finding the correct sum, and instead it is printing out a large random number. Any help is appreciated!
#include <iostream>
usingnamespace std;
constint N=10;
int main ()
{
int num [10],i,sum = 0,avg = 0;
for (int i= 0; i<10; i++)
{
cout <<"Please enter a integer"<<endl;
cin>> num[i];
}
for (int i= 0; i<10; i++)
sum=sum +num[i];
cout <<"sum of array is"<<sum<<endl;
system ("pause");
return 0;
}
Ok it works thank you so much! I just have another concern, since I have to ask the user to enter in 10 integers, is the way I have it the best way to do that?
Yes, that does work better, thanks! For extra credit on this program I can have it also find the largest and smallest numbers in the array and here's what I have:
#include <iostream>
using namespace std;
const int N=10;
int main ()
{
int num [10],i,sum=0,avg=0,maxindex=0;
for (int i= 1; i<=10; i++)
{
cout <<"Please enter integer number"<<i<< ":";
cin>> num[i];
}
for (int i= 0; i<10; i++)
sum=sum +num[i];
cout <<"The sum of the numbers in the array are:"<<sum<<endl;
for (int i=0;i<10;i++)
{
if (num[i] > num [maxindex])
maxindex=num[i];
}
cout << "The largest number in array is:" << num[maxindex];
}
{
if (num[i] < num [maxindex])
maxindex=num[i];
}
cout << "The smallest number in array is:" << num[maxindex];
}
avg=sum/10;
cout <<"The average of the numbers entered into the array is:"<<avg<<endl;
system ("pause");
return 0;
}
Its showing a lot of errors saying "cout is ambiguous" and with the brackets saying "expected a declaration."
@paulthepenguin
Doing it your way, you will be out of array bounds when you get to 10, since the array goes from 0 to 9. So, the way would be
1 2 3 4 5
for(int i = 0; i < 10; i++)
{
cout << "Enter integer number " << i+1 << ": "; // With the '+1', it will print 1 to 10, but fill the array 0 to 9.
cin >> num[i];
}
You will be in a lot trouble trying to find high and low, that way. Lets say one of the numbers in the array is 20. maxindex would equal 20, and then you use num[maxindex], and there is NO num[20].
Try this way.
1 2 3 4 5 6 7 8 9 10
int highest=num[0],lowest=num[0];
for (int i=0;i<10;i++)
{
if (highest < num[i])
highest = num [i];
if(lowest > num[i])
lowest = num[i];
}
cout << "The largest number in array is:" << highest;
cout << "The lowest number in array is: " << lowest;