Calculate array using for loop.

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;
    
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?

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];
                                  }                         
This could easily have been done with a single for loop.
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.