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

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;
}

Related

Even and odd sorting arrays

I can't get the following program to sort 'orig', 'even', and 'odd' arrays in ascending order.
The code seems fine to me, but it doesn't sort correctly at all, it will separate the array into the original even and odd lists, but the order is random and not in ascending order at all.
The output should look something like this:
Input up to 50 integers. Use a negative number to stop.
The list will be sorted into odd and even values.
Input an integer: 15
Input an integer: 8
Input an integer: 22
Input an integer: 4
Input an integer: 77
Input an integer: 19
Input an integer: 2
Input an integer: -1
Orig Even Odd
2 2 15
4 4 19
8 8 77
15 22
19
22
77
#include<iostream>
#include<iomanip>
using namespace std;
void DataIn(int Max[], int List[][50]);
void Separate(int Max[], int List[][50]);
int Lowest(int start, int N, int Vector[]);
void Sort(int Max[], int List[][50]);
void DataOut(int Max[], int List[][50]);
int main()
{
//Index: 0 = input, 1 = even, 2 = odd
int Max[3] = { 0, 0, 0 };
int List[3][50];
cout << "Input up to 50 integers. Use a negative number to stop.\n";
cout << "The list will be sorted into odd and even values.\n\n";
DataIn(Max, List);
Separate(Max, List);
Sort(Max, List);
DataOut(Max, List);
}
void DataIn(int Max[], int List[][50])
{
cout << "Input an integer: ";
cin >> List[0][Max[0]];
while (List[0][Max[0]] > 0)
{
cout << "Input an integer: ";
cin >> List[0][++Max[0]];
}
return;
}
void Separate(int Max[], int List[][50])
{
int n, type;
for (n = 0; n < Max[0]; ++n)
{
if ((List[0][n] % 2) == 0)
type = 1;
else
type = 2;
List[type][Max[type]++] = List[0][n];
}
return;
}
int Lowest(int start, int N, int Vector[])
{
int i, low = start;
for (i = start + 1; i < N; i++)
if (Vector[i] < Vector[low])
low = i;
return (low);
}
void Sort(int Max[], int List[][50])
{
int i, j, k, l;
double origSort,evenSort,oddSort;
for (i = 0; i < Max[0] - 1; ++i)
{
j = Lowest(i, Max[0], List[50]);
origSort = List[0][i];
List[0][i] = List[0][j];
List[0][j] = origSort;
k = Lowest(i, Max[1], List[50]);
evenSort = List[1][i];
List[1][i] = List[1][k];
List[1][k] = evenSort;
l = Lowest(i, Max[2], List[50]);
oddSort = List[2][i];
List[2][i] = List[2][l];
List[2][l] = oddSort;
}
}
void DataOut(int Max[], int List[][50])
{
int i;
int orig = 0, even = 1, odd = 2;
cout << "\n\n";
cout << setw(10) << "Orig" << setw(10) << "Even" << setw(10) << "Odd" << "\n\n";
for (i = 0;i < Max[0];i++)
{
if(List[0][i]>0)
cout << setw(10) << List[orig][i];
else
cout << setw(10) << " ";
if (List[1][i] > 0)
cout << setw(10) << List[even][i];
else
cout << setw(10) << " ";
if (List[2][i] > 0)
cout << setw(10) << List[odd][i] << "\n";
else
cout << "\n";
}
}
You have overcomplicated yourself too much with a two dimensional array and whatever int Max[3] is.
Things are simple: sort the original vector, then filter the odds and evens. Since you filter after you sort, the two resulting vectors will already be sorted.
Here's the C++20 solution:
int main()
{
using namespace std::ranges::views;
std::vector<int> v{15, 8, 22, 4, 77, 19, 2};
std::ranges::sort(v);
auto evens = v | filter([] (int a) { return a % 2 == 0; });
auto odds = v | filter([] (int a) { return a % 2 != 0; });
for (auto e : v)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : evens)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : odds)
std::cout << e << " ";
std::cout << std::endl;
}
You don't even need the variables to store the ranges. You can do the filter in the output loop if you want:
for (auto e : v | filter([] (int a) { return a % 2 == 0; }))
std::cout << e << " ";
std::cout << std::endl
And here's the non-ranges solution:
int main()
{
std::vector<int> v{15, 8, 22, 4, 77, 19, 2};
std::vector<int> evens;
std::vector<int> odds;
std::sort(v.begin(), v.end());
std::copy_if(v.begin(), v.end(), std::back_inserter(evens),
[] (int a) { return a % 2 == 0; });
std::copy_if(v.begin(), v.end(), std::back_inserter(odds),
[] (int a) { return a % 2 != 0; });
for (auto e : v)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : evens)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : odds)
std::cout << e << " ";
std::cout << std::endl;
}
If you for whatever reason don't want to use the standard library algorithms you must at least use the standard containers. Ditch the C arrays. And implement the solution following the same logic: sort then filter.

How to transfer elements from vector to a new array?

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;

Comparisons in Multiple Sorting Algorithms

Currently this program will generate 10 random numbers and either sort (from least to greatest), reverse sort, or shuffle them. However, when trying to list the number of comparisons made, the number of comparisons printed out are completely incorrect. For example, it prints that there were 44 comparisons with bubble sort (this is the one that varies every time but is usually around 40), 45 with selection sort, and 9 with insertion sort. For now I'm only running the program with numbersSorted() just to make sure the comparisons work.
How can I print the correct number of comparisons made with each sorting method?
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int count1 = 0; //bubble
int count2 = 0; //selection
int count3 = 0; //insertion
vector<int> numbersSorted(int n);
vector<int> numbersReversed(int n);
vector<int> numbersShuffled(int n);
int main() {
srand(time(0));
numbersSorted(10);
//numbersReversed(10);
//numbersShuffled(10);
return 0;
}
vector<int> numbersSorted(int n)
{
vector <int> v(n);
for (auto &x : v)
x = rand() % 100;
cout << "Original list to be sorted: ";
for (auto x : v)
cout << x << " ";
cout << "\n\n";
// bubble sort
bool swapped = true;
for (int pass = 0; pass <= n - 2 && swapped; ++pass)
{
swapped = false;
for (int i = 0; i <= n - pass - 2; ++i)
{
++count1;
if (v.at(i) > v.at(i + 1))
{
swap(v[i], v[i + 1]);
swapped = true;
}
}
}
cout << "Bubble sort sorted: ";
for (auto x : v)
cout << x << " ";
cout << "\n";
cout << "There were " << count1 << " comparisons with bubble sort.\n" <<
endl;
// selection sort
for (int pass = 0; pass <= n - 2; ++pass)
{
// Find least element remaining in the list starting at index pass
int minIndex = pass;
// i = minIndex + 1, minIndex + 1, ..., n - 1
for (int i = minIndex + 1; i < n; i++)
{
++count2;
if (v[i] < v[minIndex])
{
minIndex = i;
}
// The element at index i is smaller than what I thought was the
min
}
swap(v[pass], v[minIndex]);
}
cout << "Selection sort sorted: ";
for (auto x : v)
cout << x << " ";
cout << "\n";
cout << "There were " << count2 << " comparisons with selection sort.\n" <<
endl;
//insertion sort
for (int pass = 0; pass <= n - 2; ++pass) {
// Take the element at pass+1 and move it to the left until it's in the
// right spot (i.e., as long as it's in the wrong spot).
// for i = pass, pass-1, ..., 0 while L[i] > L[i+1]
++count3;
for (int i = pass; i >= 0 && v[i] > v[i + 1]; --i) {
swap(v[i], v[i + 1]);
}
}
cout << "Insertion sort sorted: ";
for (auto x : v)
cout << x << " ";
cout << "\n";
cout << "There were " << count3 << " comparisons with insertion sort.\n" <<
endl;
//return v;
}
vector<int> numbersReversed(int n)
{
vector <int> v(n);
for (auto &x : v)
x = rand() % 100;
cout << "Original list to be reversed: ";
for (auto x : v)
cout << x << " ";
cout << "\n\n";
// bubble sort
bool swapped = true;
for (int pass = 0; pass <= n - 2 && swapped; ++pass)
{
swapped = false;
for (int i = 0; i <= n - pass - 2; ++i)
{
++count1;
if (v.at(i) > v.at(i + 1))
{
swap(v[i], v[i + 1]);
swapped = true;
}
}
}
//reverse the content of the vector
reverse(v.begin(),v.end());
cout << "Bubble sort reversed: ";
for (auto x : v)
cout << x << " ";
cout << "\n";
cout << "There were " << count1 << " comparisons with bubble sort.\n" <<
endl;
// selection sort
for (int pass = 0; pass <= n - 2; ++pass)
{
// Find least element remaining in the list starting at index pass
int minIndex = pass;
// i = minIndex + 1, minIndex + 1, ..., n - 1
for (int i = minIndex + 1; i < n; i++)
{
++count2;
if (v[i] < v[minIndex])
// The element at index i is smaller than what I thought was the
min
minIndex = i;
}
swap(v[pass], v[minIndex]);
}
reverse(v.begin(),v.end());
cout << "Selection sort reversed: ";
for (auto x : v)
cout << x << " ";
cout << "\n";
cout << "There were " << count2 << " comparisons with selection sort.\n" <<
endl;
// insertion sort
for (int pass = 0; pass <= n - 2; ++pass) {
// Take the element at pass+1 and move it to the left until it's in the
// right spot (i.e., as long as it's in the wrong spot).
// for i = pass, pass-1, ..., 0 while L[i] > L[i+1]
++count3;
for (int i = pass; i >= 0 && v[i] > v[i + 1]; --i) {
swap(v[i], v[i + 1]);
}
}
reverse(v.begin(),v.end());
cout << "Insertion sort reversed: ";
for (auto x : v)
cout << x << " ";
cout << "\n";
cout << "There were " << count3 << " comparisons with insertion sort.\n" <<
endl;
}
vector<int> numbersShuffled(int n)
{
vector<int> v(n);
for (auto &x : v)
{
x = rand() % 100;
++count1;
}
cout << "Numbers Shuffled: ";
for (auto x : v)
cout << x << " ";
cout << "\n";
cout << "There were " << count1 << " comparisons made. " << endl;
}

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;
}
}