Reputation: 122
The directions are: Design and code a program that asks the user how many numbers from which to determine an average. Then prompt the user for the integer values and sum them to a total. Display the sum of the numbers and the calculated average with appropriate accompanying text. The average should be shown with 1 decimal place. Repeat the process until the user enters zero (0) as the number of values to be averaged. You may use either a "while" loop or a "do…while" loop for the main program loop.
Use one function to read and sum the values and another function to display the sum and average. Use a "for" loop to read and sum the values.
The for loop doesn't seem to be executing, but I can't figure out why.
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int sumNums(int amount, int, int, int);
void displaySum(int sum, int avg);
main()
{
int amount = 0;
cout <<"How many numbers do you wish to average? ";
cin >> amount;
int avg = 0, sum = 0;
while (amount != 0)
{
for (int lim = 0; lim == amount; lim++)
{
int number = 0;
cout <<"Enter a value"<< endl;
cin >> number;
sumNums(amount, number, sum, avg);
displaySum (sum, avg);
}
}
}
int sumNums (int amount, int number, int sum, int avg)
{
sum = sum + number;
avg = sum / amount;
return sum, avg;
}
void displaySum (int sum, int avg)
{
cout <<"The sum is "<< sum <<" and the average is "<< avg << endl;
}
Upvotes: 0
Views: 136
Reputation: 1850
for (int lim = 0; lim == amount; lim++) // so wrong...
change to
for (int lim = 0; lim < amount; lim++)
Upvotes: 0
Reputation: 8942
for (int lim = 0; lim == amount; lim++)
Here you set lim to 0 and the code runs only if amount is not 0. In your for you execute only if lim equals amount which never happens.
Whatever your condition is, it must evaluate to true for every iteration that you want to do.
Most probably, you will want to execute until lim equals amount so that means that you want it to execute for every iteration where lim is lower than amount.
for(int lim = 0; i < amount; lim++)
Upvotes: 2