Calculate array using for loop.
Sep 30, 2010 at 4:28pm UTC
What ever numbers i type the sum of 5 number be allways -1, why its keep coming up like that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
{
int iArray[5];
int iCounter;
cout << "Type five number:" ;
for (iCounter=0;iCounter<5;iCounter++)
{
cin >> iArray[iCounter];
}
int sum;
for (iCounter=0;iCounter<5;iCounter++)
{
sum+=iArray[iCounter];
}
cout << sum;
Sep 30, 2010 at 4:35pm UTC
What's the value of sum at line 10?
What's the value of iArray[iCounter] at line 14?
What's the value of sum for each step in the loop after line 14?
Sep 30, 2010 at 4:50pm UTC
Works now ty PanGalactic
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int iArray[5];
int iCounter;
cout<<"Type five number:" ;
for (iCounter=0;iCounter<5;iCounter++)
{
cin >> iArray[iCounter];
}
int sum=0;
for (iCounter=0;iCounter<5;iCounter++)
{
sum+=iArray[iCounter];
}
Sep 30, 2010 at 6:19pm UTC
This could easily have been done with a single for loop.
Sep 30, 2010 at 8:02pm UTC
haha yeah..
@whb191:
you can have more than 1 operation in a loop ;)
so just add the sum+=iArray[iCounter];
in the 1st loop and remove the second.
Gives you a much cleaner code (and more easy to understand :)
Cheers!
Topic archived. No new replies allowed.