I'm stuck in a problem , help please.

Can anyone help me out with this homework ? 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.

This is what I have so far , but I don't if it's correct.

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

using namespace std;

int main()

{
	int value;
	int count = 0;
	int total = 0;

	cout <<"enter an integer - 1 to end:"<<endl;
	cin 
	
	for (; value != -1;) {
	
		total += value;
		++count ;

		System ("pause");
	}

	return 0;
To start off, you are not taking anything in - cin.
Also I doubt that is the way your teacher wanted you to use a for loop since it is really just a while loop. I would suggest first storing the values in a container and then use the for loop to do the calculations.
closed account (j3Rz8vqX)
Line 13 error. You cannot cin a for-loop.
You could encapsulate a cin in a for-loop, though.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main()
{
    int value;
    int count = 0;
    int total = 0;
    
    while(cin>>value && value!=-1 && ++count)//Evaluates from left to right, only if prior statement is true.
    {
        //Try It!: Accumulate total.
    }
    //Try It!: Calculate average (total/count);
    //Try It!: Possibly print the necessary results.
    return 0;
}
Edit: OR
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main()
{
    int value;
    int count = 0;
    int total = 0;

    for(count=0;cin>>value && value!=-1;++count)
    {
        //Try It!: Accumulate total.
    }
    //Try It!: Calculate average (total/count);
    //Try It!: Possibly print the necessary results.
    return 0;
}
Last edited on
Thanks everyone for all the help but the professor wants it in a FOR loop and not WHILE.

how can I convert while to for ???
Last edited on
closed account (j3Rz8vqX)
"New"-friendlier version of the for-loop, provided above:
1
2
3
4
5
6
7
8
9
10
11
12
    for(value=0;value!=-1;++count)
    {
        cin>>value;
        if(value!=-1)
        {
            //Try It!: Accumulate total.
        }
        else
        {
            --count;//Found a negative 1, decrement to counter increment of count
        }
    }
Thank you , I'm trying it ...
I still stuck :-(
closed account (j3Rz8vqX)
With what:

Accumulating total? (Total equal to itself plus the new value)

Calculating average? (Average equal to total divided by count)

Tips: Cast to float during average computation and store average to a floating variable if you need to, else print average as a cast of float(total) divided by count.

What do you have so far, as of now.
Last edited on
Thanks for all the help buddy .
Topic archived. No new replies allowed.