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.
#include <iostream>
usingnamespace 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.
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>
usingnamespace 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>
usingnamespace 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;
}
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.