Loops Sum

Mar 1, 2016 at 4:46pm
Write a program that accepts numbers from the user, adds them, and outputs the average. The numbers should be summed until user enters -1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream> 
using namespace std;

   // USING A FOR LOOP 
   
   
   int main()
   {
       double num = 0, sum =0 , average =0;
       
       for(int k = 0; k < 6; k++)
         {
               
          cout<<"Enter a number"<<endl;
          cin>>num;
          sum = sum + num;
          }
          
         average = sum/6;
         cout<<"AVERAGE IS "<<average<<endl;
         
         system ("pause");
         return 0;
   }


Help would very helpful. Thank you.
Last edited on Mar 1, 2016 at 5:26pm
Mar 1, 2016 at 5:15pm
Your program expects the user to enter exactly six numbers. That is not what the problem statement says. The problem statement says to accept input until the user enters -1. That is usually done with a while loop rather than a for loop.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.



Mar 1, 2016 at 5:16pm
First, please use the code tags when posting code. See http://www.cplusplus.com/articles/jEywvCM9/

Your code in tags, with tiny (style) tweaks:
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
#include <iostream>

int main()
{
  using std::cout;
  using std::cin;

  double num = 0; // Are the values floating point values?
  double sum = 0;

  for ( int k = 0; k < 6; ++k ) // 6? Instructions do not say 6.
  {
    cout << "Enter a number\n";
    cin >> num; // What if the user types a non-number?
    // The input will fail and the std::cin will be in error state
    // All following input would fail too
    // One should check success and handle errors

    // What if -1==num?  One can break out from a loop
    // If the use of for loop demanded? while is simpler for this

    // If num is double, then -1==num is not exact.  Rather: abs(-1 - num) < epsilon

    sum = sum + num; // There is a shorter operator: sum += num;
  }

  double average = sum / 6;  // Again, the 6.  The input should keep count of values.

  cout << "AVERAGE IS " << average << '\n';
  return 0;
}
Topic archived. No new replies allowed.