HOMEWORK

Can anyone help me out with this home work ? I'm not being able to figure it out. I'm new to C++

Write a program that uses for statement to calculate the average of several integers. Assume the last value read is the sentinel -1. For example, the sequence 10 8 11 7 23 56 -1 indicates that the program should calculate the average of all the values preceding -1.
Last edited on
Well, I am not going to do your homework for you, I don't like doing that. But I will give you enough help that will practically give you the answer.
I wrote the program you explained, and it worked out fine. Here are a couple tips:

1) Make sure that you put all the numbers you add in parentheses. Like this:
int blah = (x + x + x + x + x + x + x) / 7;

Well. That was my only tip, haha. Think about math class, where calculators were not as smart as humans, and you have to help them out a bit by using parentheses. Well, good news. Calculators are just computers. You are at a computer, trying to make it a calculator. I tried it without parentheses, and I didn't get the right answer. Anyway, glad to help!
It would look something like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
    double avg = 0, nums = 0;
    for (bool rdy = false; rdy == false;)
    {
        double n;
        std::cout << "Enter a number: ";
        std::cin >> n;
        if (n == -1)
            rdy = true;
        else
        {
            avg+= n;
            nums++;
        }
    }
    avg = (avg/nums);
    std::cout << "The average of these numbers is: " << avg;
}


hope that helps
or either:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> data;
    int x;
    while(std::cin >> x && x != -1)
        data.push_back(x);
    double average = std::accumulate(data.begin(), data.end(), 0.0) / data.size();
    std::cout << average;
}
#include <iostream>

int main()
{
    int   sum = 0;
    int count = 0;
    int   tmp = 0;
    while(std::cin >> tmp && tmp != -1) {
        sum += tmp;
        ++count;
    }
    double average = static_cast<double>(sum) / count;
    std::cout << average;
}

Last edited on
but how about the program computing the average of all the values preceding and stopping when it hits -1 ???

The code keep on going . . .
Last edited on
The code keep on going . . .
Which code? All three examples should work fine.

Show input where any of three programs continue looping after -1 is entered.
Oops , I made a mistake while I was typing sorry for that . The coding is working fine .

The only problem now is that I need it in FOR STATEMENT and not While how can I switch ?

while( something ) is equal to for( ; something ; )
Thank you for all the help . . .
Topic archived. No new replies allowed.