I am in a programming 2 class and I have a question that ask me to create a for loop and to have the user to input 5 numbers and to find the average and sum from those numbers. I am having troubles figuring out a way to do this. Any help to get this off the ground would be awesome. Thank you!
int sum = 0; // stores the sum.
for(int i = 0; i < 5; i++) // Runs 5 times.
{
// Inside the loop. First you take the input, then you add it to the variable "sum".
}
// Once you are outside the loop. The variable "sum" will be equal to the total of the
// numbers entered. Then all you have to do is divide sum by 5 to get the average.
int num1, num2, num3, num4, num5;
int sum = 0;
float avg;
int main()
{
cout << "Enter five numbers and you will get the sum and average of those numbers." << endl;
cin >> num1 >> num2 >> num3 >> num4 >> num5;
for(int i = 0; i < 5; i++)
{
sum + num1 + num2 + num3 + num4 + num5;
}
avg = sum / 5;
cout << sum << endl;
cout << avg << endl;
I keep getting 0's for both average and sum. You would think that you would at least get some sort of number. I may be doing something wrong though. My programming is rusty as I have touched a computer all summer. Thanks again!
You've come quite a bit, but I think you misunderstood my instructions, read it again. Inside the loop is where you are supposed to ask the user for input. You only need 1 line for that, since the loop already runs 5 times.
Inside the loop you do this. Take input, put it in sum. Give this another go, if you are still having trouble, I'll help you out.
int num1, num2, num3, num4, num5;
int sum = 0;
int total;
float avg;
int main()
{
cout << "Enter five numbers and you will get the sum and average of those numbers." << endl;
for(int i = 0; i < 5; i++)
{
num1 + sum;
cin >> num1;
}
total = sum + num1;
avg = total / 5;
cout << total << endl;
cout << avg << endl;
int input;
int sum = 0;
float avg;
int main()
{
cout << "You will enter five numbers to get the sum and average of those numbers." << endl;
for(int i = 0; i < 5; i++)
{
cout << "Enter a number." << endl;
cin >> input;
sum += input;
}
avg = sum / 5;
cout << "The sum is: " << sum << endl;
cout << "The average is: " << avg << endl;