How to have "x" many cin based on user input

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
#include <iostream>

using namespace std;

int num_nums; //number of numbers that the user wants to average
int num1;
int num2;
int num3;

int main()
{
    cout << "How many numbers do you want to average: ";
    cin >> num_nums;
    cout << "Enter numbers here: ";

    if (num_nums == 1) //if user wants to average 1 number, go here
        {
        cin >> num1;
        cout << "The average is: " << num1;
        }
    else if (num_nums == 2) //if user wants to average 2 numbers, go here
        {
        cin >> num1 >> num2;
        cout << "The average is: " << (num1 + num2)/2;
        }
    else if (num_nums == 3) //if user wants to average 3 numbers, go here
        {
        cin >> num1 >> num2 >> num3;
        cout << "The average is: " << (num1 + num2 + num3)/3;
        }

return 0;

}


This program will allow the user to chose an amount of numbers (up to 3) and get an average of the numbers that he inputs. I want to be able to do it to infinity, but I cannot figure out how to get cin >> "amount of num_nums the user selected"
Last edited on
Get number of numbers from user.
Then loop from i=0 to i=numberOfNUmbers-1
{
get next number
put it on end of vector
}
now sum vector and calculate average
You can use for-statement as for example

1
2
3
4
5
6
7
8
9
10
11
int sum = 0;
for ( int i = 0; i < num_nums; i++ )
{
   int num;
   
   cin >> num;

   sum += num;
}

int average = sum / num_nums;

Last edited on
vlad:

I did it, and it worked! Thank you! But I have two quick questions.

1) I did not put sum=0 before, and it worked. Why did you put it? Is it necessary?

2) What is the difference between putting ++i and i++ (on the last part of the for loop). I am yet to understand that, and for this program, either gives me the correct result. Do you mind explaining that a little bit please?

Thank you!
I do not know where you put sum because I do not see your code. As for ++i and i++ then for fundamental types these expressions used in loops have no a difference.
Ok thanks the ++i and i++ was confusing me but you just helped!

and basically I wrote the same code as you, except don't have sum=0 at all and it still works.
It depends on where sum is declared. If it is declared before the main then there is no problem because variables with static storage class are initialized by zero. If it declared inside the main then the result is undefined.
Last edited on
You are a great teacher! Thank you!
Topic archived. No new replies allowed.