### Definite Iterations

I want to have a program that finds the sum of a group of numbers. I would like for it to ask how many numbers total there will be, and then ask for the input.

So output like -

How many numbers do you want to input? 4

Input 1:1
Input 2:2.5
Input 3:10
Input 4:3

Sum = 16.5
Average = 4.13

-----
I read that you can use a definite iteration which takes the amount of times specified, and executes the statement that amount of times. So in this case, 4 would be the times specified. I don't know what code I would use to get that to happen though.
its called a "for" loop:

for(int i = 0; i = /*some qualifying value*/; i++)
{

}

If you wanted to loop 4 times, the qualifying value would be

i < 4;

Last edited on
 ``12345678910111213141516171819202122232425`` ``````#include int main() { unsigned int n; std::cout << "How many numbers do you want to input: "; std::cin >> n; double sum = 0.0; for ( unsigned int i = 0; i < 4; i++ ) { double value = 0.0; std::cout << "Inpun #1: "; std::cin >> value; sum += value; } std::cout << "\nSum = " << sum << std::endl; std::cout << "Average = " << sum / n << std::endl; return 0; } ``````
Last edited on
Alright, I took what you did, and rewrote it like this -

 ``123456789101112131415161718192021222324252627`` ``````#include "stdafx.h" #include using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int n; int x; cout << "How many numbers you want to input? "; cin >> n; double sum = 0.0; for (int i = 0; i < n; i++ ) { double x = 0.0; cout << "Input # "; cout << i+1; cout << "-->"; cin >> x; sum += x; } cout << "\nSum = " << sum << endl; cout << "Average = " << sum / n << endl; return 0; }``````
Is there a way that I could do it so that so that I could just have it not ask for how many numbers, but just keep asking for a number? And then if they enter 0 it stops asking?

so example output would be:
Please enter the next number: 21
Please enter the next number: 0

You have entered 0.
Also, for the code I wrote above, is there a way to always round to the nearest 10th or 100th?
Actually, I figured out the rounding to nearest 100th -

 ``12345678910111213141516171819202122232425262728293031`` ``````// project2.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include using namespace std; #include int _tmain(int argc, _TCHAR* argv[]) { int n; int x; cout << "How many numbers you want to input? "; cin >> n; double sum = 0.0; for ( unsigned int i = 0; i < n; i++ ) { double x = 0.0; cout << "Input # " << i+1 << "-->"; cin >> x; sum += x; } cout << setprecision(2) << fixed << "\nSum = " << sum << endl; cout << setprecision(2) << fixed << "Average = " << sum / n << endl; return 0; }``````

Topic archived. No new replies allowed.