Declaring variables within loops?

I am trying to make a simple program that will tell me the mean of a set of numbers. The problem I have is that the user must input the exact amount of numbers as I have variables. How do I make a loop system that will take a new input each time it runs and attach a new variable name to that input so the user can input as many or as little variables as they want?

Here is what i have so far no loops involved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#import <iostream>
#import <cmath>
#import <iomanip>

using namespace std;

int main() {
	cout.setf(ios::fixed);
	cout.setf(ios::showpoint);
	cout.precision(2);
	
	float x1;
	float x2;
	float x3;
	float x4;
	float x5;
	
	cout << "Please give me 5 numbers:\n";
	
	cin  >> x1;
	cin  >> x2;
	cin  >> x3;
	cin  >> x4;
	cin  >> x5;
	
        cout << endl;
	
	float mean;
	mean = (x1 + x2 + x3 + x4 + x5) / 5;

	cout << mean << "\n\n";
        
        return 0;
}


Note: There is much more I am going to do with the numbers later.
You might want to utilize a dynamic array in this case or vector.

Here is an example

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

int main ()
{
    double* values;
    int n;
    double total = 0;

    // n is the total number of values user is providing
    std::cin >> n;

    values = new double [n];

    for( int i = 0 ; i < n ; i ++ ) {
        std::cin >> values[i];
        total += values[i];
    }

    std::cout << total / n;

    return 0;
}


You can use this with a notepad that has a list of all values
input.txt

10
1 4 -3 6.7 3
7 56 -5 78 23


If you are using Windows, you can open cmd and provide input from a file like this
example.exe < input.txt



If you must receive input from a user directly without using file, you can simply ask user to type the total number of values they are providing and then enter each value;

There is a way to just receive values only and not ask user to enter the total n. For brevity, I will skip it, but if you must know how to do it, let me know.

The point is if you want to store multiple values in a variable, you use loop and array.
Last edited on
Okay. Thanks. That really helps.
Of course, you don't actually need to store the numbers to get a mean. You can just keep a running sum and a count.
Topic archived. No new replies allowed.