Ty F.

asked • 03/17/21

C++ Factorial Problem using Vectors

I am new to C++ and am struggling with a recent practice problem, I have some code so far but can't figure out how to get the variable to update to correctly give the next factorial. Here is the full problem prompt:


Write a program that gets a list of integers (which are chosen from values between 0 and 8 inclusive) from the user, and stores the factorial of each integer in a vector. The first integer indicates how many numbers are in the list and should not be stored in the vector. The program should print out the vector values. (Hint: n! = 1 for n=0 or n=1; and n! = 1 x 2 x … x (n-1) x n for n >1.)

For example, given the following input:
5 1 2 3 0 4

The first number, 5, means there will be 5 numbers in the vector and we are going to store the factorials of the remaining numbers.

Therefore, the following output will be produced:
1 2 6 1 24

which is the result of 1!, followed by 2!, then 3!, 0!, and finally 4!

Here is the code I have come up with so far:


#include <iostream>

#include <vector>

using namespace std;


int main() {

int NUM_ELEMENTS, userVals;

vector<int> userList;

vector<int> factorialList;

int factorialVal = 1;

unsigned int i;

unsigned int j;

cout << "enter a list of values" << endl;

cin >> NUM_ELEMENTS;

for (i = 0; i < NUM_ELEMENTS; ++i) {

cin >> userVals;

userList.push_back(userVals);

}

for (i = 0; i < NUM_ELEMENTS; i++) {

for (j = 1; j <= userList.at(i); j++) {

factorialVal = userList.at(i);

factorialVal = factorialVal * j;

}

factorialList.push_back(factorialVal);

cout << factorialList.at(i) << " ";

}

return 0;

}


1 Expert Answer

By:

Patrick B. answered • 03/17/21

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.