How to transfer elements from vector to a new array? - c++

I need to transfer elements from the total costs (int totalCosts) into a new array to be called costs[]. I tried doing this at the end of the code but when I tried to access the first element in the array, it shows ALL the total costs from the output. I only needed to access the first one.
// ******** CREATE "example.txt" IN THE FOLDER THAT HAS THE PROJECT'S .CPP FILE ********
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <iterator>
using namespace std;
class vehicle_capacities {
public:
int lw, vw;
};
double nearest_ten(double n)
{
return round(n / 10.0 + 0.4) * 10.0;
}
bool cmp_fn(int a, int b)
{
return a > b;
}
int main()
{
int cw;
vehicle_capacities cap;
cap.lw = 30;
cap.vw = 10;
ifstream myfile("example.txt");
if (myfile.is_open()) {
myfile >> cw;
myfile.close();
}
else {
cout << "Unable to open file" << endl;
}
cout << "Amount of cargo to be transported: " << cw;
cw = nearest_ten(cw);
cout << "(" << cw << ")" << endl;
int maxl = cw / cap.lw; // maximum no. of lorries that can be there
vector<pair<int, int>> solutions;
//vector<int> costs;
vector<int>::iterator it;
// for the inclusive range of 0 to maxl, find the corresponding no. of vans for each variant of no of lorries
for (int l = 0; l <= maxl; ++l) {
bool is_integer = (cw - l * cap.lw) % cap.vw == 0; // only if this is true, then there is an integer which satisfies for given l
if (is_integer) {
int v = (cw - l * cap.lw) / cap.vw; // no of vans
solutions.push_back(make_pair(l, v));
}
}
cout << "Number of mini-lorries: ";
for (auto& solution : solutions) {
cout << solution.first << " ";
}
cout << "\n";
cout << "Number of vans: ";
for (auto& solution : solutions) {
cout << solution.second << " ";
}
cout << "\n";
cout << "Total cost: ";
// LORRY COST = $200, VAN COST = $45
for (auto& solution : solutions) {
int totalCosts = (solution.first * 200) + (solution.second * 45);
cout << totalCosts << " ";
}
/*for (auto& solution : solutions) {
int totalcosts = (solution.first * 200) + (solution.second * 45);
costs.push_back(totalcosts);
for (it = costs.begin(); it < costs.end(); it++) {
cout << *it << " ";
}
}*/
cout << endl;
// Comparison between both vehicles, highest amount = trips needed
cout << "Trips Needed: ";
for (auto& solution : solutions) {
int a = solution.first;
int b = solution.second;
if (a > b) {
cout << a << " ";
}
else if (b > a) {
cout << b << " ";
}
else if (a == b) {
cout << a << " ";
}
}
cout << endl;
cout << "Lowest #1: ";
for (auto& solution : solutions) {
int totalCosts[] = { (solution.first * 200) + (solution.second * 45) };
int elements = sizeof(totalCosts) / sizeof(totalCosts[0]);
sort(totalCosts, totalCosts + elements, cmp_fn);
for (int i = 0; i < elements; ++i) // print the results
cout << totalCosts[i] << " ";
cout << totalCosts[0] << " ";
}
// *** FOR SORTING ELEMENTS IN ARRAY LOW TO HIGH ***
/*int array[] = { 1,10,21,55,1000,556 };
int elements = sizeof(array) / sizeof(array[0]); // Get number of elements in array
sort(array, array + elements);
for (int i = 0; i < elements; ++i) // print the results
cout << array[i] << ' ';*/
return 0;
}
Do update if you have any solutions, thank you.
(Note that you have to create "example.txt" in project file.

You need to dynamically allocate your array.
int elements = solution.size();
int *totalCosts = new int[elements];
int j= 0;
// transfer data
for (auto& solution : solutions) {
totalCosts[j++] = (solution.first * 200) + (solution.second * 45);
}
sort(totalCosts, totalCosts + elements, cmp_fn);
for (int i = 0; i < elements; ++i) // print the results
cout << totalCosts[i] << " ";
cout << totalCosts[0] << " ";
delete[] totalCosts;

Related

How can I convert for loops into for-each loops?

My task is to convert my for loops into for-each loops.
The task begins with creating a two dimensional array 6x30. This represents 6 classes of 30 students each. Each position in the array contains a random number between 55 and 100 which represents a student score.
Next I display that array to the console.
Next I calculate the average score of each class.
Next I find the highest average among the 6 classes and display that to the screen.
I am using Xcode on MacBook Pro.
Question: How can I properly convert my for loops into for-each loops?
My code is below:
#include <iostream>
#include <iomanip>
using namespace std;
const int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;
void bubbleSort(int arr[], int n){
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1])
swap(arr[j], arr[j + 1]);
}
}
}
void classGradeGeneration() {
int arrayOne[NUM_CLASSES][NUM_STUDENTS_PER_CLASS], classAverage[NUM_CLASSES];
//Generating random average student scores until array filled
for (int classNumber = 0; classNumber < NUM_CLASSES; classNumber++) {
for (int column = 0; column < NUM_STUDENTS_PER_CLASS; column++) {
arrayOne[classNumber][column] = rand() % 46 + 55;
}
}
//Displaying array of student scores
for (int classNumber = 0; classNumber < NUM_CLASSES; classNumber++) {
cout << "Class " << classNumber + 1 << ": ";
for (int column = 0; column < NUM_STUDENTS_PER_CLASS; column++) {
cout << setw(3) << arrayOne[classNumber][column] << " ";
classAverage[classNumber] += arrayOne[classNumber][column];
}
cout << endl;
}
cout << endl;
int averageScore, averageOfClasses[NUM_CLASSES];
//Displaying average class scores
for (int temp = 0; temp < NUM_CLASSES; temp++) {
averageScore = classAverage[temp] / NUM_STUDENTS_PER_CLASS;
cout << "Class " << temp + 1 <<" Average score: " << averageScore << endl;
averageOfClasses[temp] = averageScore;
}
cout << endl;
bubbleSort(averageOfClasses, NUM_CLASSES); // Sorting average scores highest to lowest
cout << endl;
cout << "The highest average score is: " << averageOfClasses[0];
cout << endl;
}
int main () {
srand(time(NULL));
classGradeGeneration();
cout << endl << endl;
}
Below is a sample output:
You may use range-based for with std::array since C++11
constexpr int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;
std::array<std::array<int, NUM_STUDENTS_PER_CLASS>, NUM_CLASSES> arr;
for (/*const*/ auto& ln : arr) {
std::cout << "LINE" << std::endl;
for (/*const*/ auto& elem : ln) {
std::cout << "elem" << std::endl;
}
}
or for_each if you want
std::for_each(arr.begin(), arr.end(), [](/*const*/ auto& line) {
std::cout << "LINE" << std::endl;
std::for_each(line.begin(), line.end(), [](/*const*/ auto& elem) {
std::cout << "elem" << std::endl;
});
});
But I prefer range-based for in this case.
If you use c-style array then for_each arguments will be pointers, not iterators.
int arr[NUM_CLASSES][NUM_STUDENTS_PER_CLASS], classAverage[NUM_CLASSES];
std::for_each(std::begin(arr), std::end(arr), [](/*const*/ auto& line) {
std::cout << "LINE" << std::endl;
std::for_each(std::begin(line), std::end(line), [](/*const*/ auto& elem) {
std::cout << "elem" << std::endl;
});
});
So your code may look like this
constexpr int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;
std::array<std::array<int, NUM_STUDENTS_PER_CLASS>, NUM_CLASSES> arr;
// set random values
for (auto& ln : arr) {
for (auto& elem : ln) {
elem = std::rand() % 100;
}
}
// calculate
float avgScore = 0.0F;
for (const auto& ln : arr) {
const auto avgGroupScore = std::accumulate(std::begin(ln), std::end(ln), 0.0F) / (std::end(ln) - std::begin(ln));
avgScore = std::max(avgScore, avgGroupScore);
std::cout << "avg group score=" << avgGroupScore << "; current avgScore=" << avgScore << std::endl;
}

How to make an output file of n*n matrix,by taking n from the user, with the numbers generated in pairs?

Currently I have a pre-made 6X6 matrix in a text file like this:
2 6 3 1 0 4
4 2 7 7 2 8
4 7 3 2 5 1
7 6 5 1 1 0
8 4 6 0 0 6
1 3 1 8 3 8
and I made a code that is reading from a file i have made. However I want to have user make a grid for themselves (i.e. 3X3 or 10X10). Which then writes to a text file automatically like in similar fashion and then have that read-in instead. It is a basic memory match card game, so I need to have rand() which generates equal pair so the game can be over when every pair in the grid has been found. Thank you so much for your time!
/*Here are the snippets of my code*/
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <fstream>
#include <string>
#include <numeric>
#include <limits>
using namespace std;
//global 2d vectors that are associated with the game
vector<vector<int> > game_grid;
vector<vector<int> > hidden_grid;
vector <vector<int> > guessed;
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
for (int i = 0; i < 6; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < 6; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
return;
}
void print_grid() {
cout << "Game grid" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
cout << game_grid[i][j] << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
}
void print_hidden_grid(int r1 = -1, int r2 = -1, int c1 = -1, int c2 = -1) {
cout << "Attempt:" << endl;
if (r1 != -1) {
hidden_grid[r1][c1] = game_grid[r1][c1];
}
if (r2 != -1) {
hidden_grid[r2][c2] = game_grid[r2][c2];
}
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
if (r1 != -1) {
if (game_grid[r1][c1] == game_grid[r2][c2]) {
guessed[r1][c1] = 1;
guessed[r2][c2] = 1;
cout << "You have a match!" << endl << endl;
}
else {
hidden_grid[r1][c1] = -1;
hidden_grid[r2][c2] = -1;
}
}
cout << endl << endl;
}
void print_current_grid() {
cout << "Current Grid:" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl << endl;
}
.......
If I well understand you want to auto detect the size of the matrix when you read it ? If yes you can do something like that in initialize_grid :
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
// detect size
int size = 0;
string line;
if (!getline(input_file, line))
return;
istringstream iss(line);
while (iss >> num)
size += 1;
input_file.clear();
input_file.seekg(0);
for (int i = 0; i < size; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < size; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
}
and else where you replace 6 by game_grid.size() (using size_t rather than int to type the indexes)

how I can print an array as a vector form

I want to cout an array as a row vector but when I write:
int main() {
int B[3]={0};
for (int w = 0; w <2; w++) {
cout <<"B="<<" "<< B[w] << " ";
}
cout << endl;
return 0;
}
The output is B=0 B=0
But I want output to be like:
B=(0 0)
For a fixed size array of only I would probably even prefer a oneliner like this, because I can read it at first glance:
cout << "B=(" << B[0] << " " << B[1] << " " << B[2] << ")\n";
For a container B with a dynamic or very high number of elements n, you should probably do something like this:
cout << "B=(";
if(n > 0)
{
cout << B[0];
// note the iteration should start at 1, because we've already printed B[0]!
for(int i=1; i < n; i++)
cout << ", " << B[i]; //I've added a comma here, so you get output like B=(0, 1, 2)
}
cout << ")\n";
This has the advantage, that no matter what number of elements, you don't end up with trailing commas or unwanted whitespace.
I'd reccommend making a generic (template) function for the purpose of printing array/std::vector content anyways - it's really useful for debugging purposes!
int main() {
int B[3] = { 0 };
cout << "B=(";
for (int w = 0; w < 3; w++) {
cout << B[w];
if (w < 2) cout << " ";
}
cout << ")" << endl;
return 0;
}
Output should be now:
B=(0 0 0)
The simplest way to do this is:-
#include<iostream>
using namespace std;
int main()
{
int B[3]={0};
cout << "B=(";
for (int w = 0; w < 3; w++)
{
cout << B[w] << " ";
}
cout << ")" << endl;
return 0;
}
the output will be B= (0 0 0 )
You can try this one if you want:
#include <iostream>
using namespace std;
int main() {
int B[3]={0};
cout << "B=(";
for (int w = 0; w <2; w++) {
cout << B[w];
if(w != 1) cout << " ";
}
cout << ")" << endl;
cout << endl;
return 0;
}
The output is:
B=(0 0)
The line if(w != 1) checks whether you 've reached the last element of the array. In this case the last index is 1, but in general the if statement should be: if(w != n-1) where n is the size of the array.

whatever i use as inputs, outputs are all zeros

This is a question i am working on:
Prompt the user to enter five numbers, being five people's weights. Store the numbers in a vector of doubles. Output the vector's numbers on one line, each number followed by one space.
Also output the total weight, by summing the vector's elements.
Also output the average of the vector's elements.
Also output the max vector element.
So far this is the code i have
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
int maxWeight = 0;
int temp = 0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": ";
cout << inputWeights[i]<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++) {
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
When i run this code, whatever inputs i use(for the cin>>(...)), i get all zero's as output and i do not know why. can i get some help please.
update
cleaned up the code a little by getting rid of the cout<< inputWeights[i]<< endl;
and by adjusting vector inputWeights; at the beginning of the program.But the outputs are still not exactly what they are supposed to be. Instead, only the first 2 inputted values make it as outputs. Any reason why? thanks
update this is the right or correct code. Hope it helps someone in future.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector <float> inputWeights;
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
float maxWeight = 0.0;
float temp = 0.0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": "<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++){
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
You're making a vector of size 5:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
// == 0, 0, 0, 0, 0
Then, in your input loop, you're adding new values to the end:
inputWeights.push_back (42);
// == 0, 0, 0, 0, 0, 42
Then you're outputting the first five elements which were always zero.
You need to choose one thing or the other: either set the size of the vector at the start of the program, or grow the vector with push_back for as long as there's input. Both are valid options.
You can clean up your code and fix the problems by adopting modern C++ (as in, C++11 and later) idiom. You don't need to fill your code with for(int i = 0; i < something; i++) any more. There's a simpler way.
// Size fixed in advance:
vector<float> weights(NUM_WEIGHTS);
for (auto& weight : weights) { // note it's `auto&`
cout << "\nEnter next weight: ";
cin >> weight; // if it was plain `auto` you'd overwrite a copy of an element of `weight`
}
// Size decided by input:
vector<float> weights; // starts empty this time
cout << "Enter weights. Enter negative value to stop." << endl;
float in;
while (cin >> in) {
if(in < 0) {
break;
}
weights.push_back(in);
}
In either case, you can then play with the filled vector using another range-based for:
cout << "You entered: ";
for (const auto& weight : weights) {
cout << weight << " ";
}
You'll also need to remove the cout << inputWeights[i] << endl; line from your input loop if you resize the vector during input - as written you'd be reading elements which don't exist yet, and will probably get an array-index-out-of-bounds exception.
When you create define your inputWeights you are putting 5 items into it with default values.
vector<float> inputWeights(NEW_WEIGHT);
Change it to be just
vector<float> inputWeights;
And get rid of this line in your code or comment it out
cout << inputWeights[i]<< endl;
This is what you are looking for from the requirements of your program.
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
unsigned i = 0;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " ";
}
std::cout << std::endl;
double totalWeight = 0.0;
std::cout << "The total of all weights is: ";
for ( i = 0; i < weights.size(); ++i ) {
totalWeight += weights[i];
}
std::cout << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: ";
double max = weights[0];
for ( i = 0; i < weights.size(); ++i ) {
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << max << std::endl;
return 0;
}
The culprit to your problem for seeing all 0s as output is coming from these two lines of code:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
which is the same as doing this:
vector<float> inputWeights{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
you are then looping through up to 5 elements using NEW_WEIGHT when it would be easier to use inputWeights.size() when traversing through containers.
Edit - Condensed Version
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
unsigned i = 0;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
double totalWeight = 0.0;
double max = weights[0];
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " "; // Print Each Weight
totalWeight += weights[i]; // Sum The Weights
// Look For Max Weight
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << std::endl;
std::cout << "The total of all weights is: " << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: " << max << std::endl;
return 0;
}

Print an array in C++

I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}