How would I find the sum of the elements in a vector that was inputted by a user? I tried searching for a method to do so everywhere online but couldn't really find one online that explained it really well, nor was it explained in class too much unfortunately.
So I basically have the vectors inputted by a user here, but I have no idea how to use it to take the sum of it? (printvector is only there because I have to present what the user put in to the user before telling the user the sum)
#include <iostream>
#include <vector>
using namespace std;
void fillVector(vector<int>&);
void printVector(const vector<int>&);
int main()
{
vector<int> VectorQuantities;
fillVector(VectorQuantities);
printVector(VectorQuantities);
return 0;
}
void fillVector(vector<int>& newVectorQuantities)
{
cout << "Type in a list of numbers, and type in -1 as the last number when you are finished: ";
int input;
cin >> input;
while (input != -1) {
newVectorQuantities.push_back(input);
cin >> input;
}
cout << endl;
}
void printVector(const vector<int>& newVectorQuantities) {
cout << "Vector: ";
for (unsigned int i=0; i < newVectorQuantities.size(); i++) {
cout << newVectorQuantities[i] << " ";
}
cout << endl;
}
You can use std::accumulate().
#include <algorithm>
std::vector<int> vec = ...;
int vecSum = std::accumulate(std::begin(vec), std::end(vec), 0);
The accumulate() function is really just a left fold, and by default it uses the + function to combine elements.
Try this:
void printSum(const vector<int>& newVectorQuantities) {
cout << "Sum: ";
int sum = 0;
for (unsigned int i=0; i < newVectorQuantities.size(); i++) {
sum = sum + newVectorQuantities[i];
}
cout << sum << " ";
}
(Using your style for the function, not modern C++.)
Related
I am learning c++ and i have a problem with filling a vector with the input from the user. wWenever i try to run my code, a window pops-up with 'vector subscript out of range' written in it.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int s(0), values(0);
vector <int> grades;
cout << "Enter the number of grades you want to enter: \n";
cin >> s;
cout << "Enter the values:";
for (int i(0); i < s; i++)
{
cin >> values;
grades.push_back(values);
}
int grades_size(grades.size());
int average(0);
for (int m(0); m <= grades_size; m++)
{
average += grades[m];
}
average /= grades_size;
cout << "Your average is" << average;
return 0;
}
You can read things from input using streams.
The following example shows how to use the succinct syntax of ranges to do that:
#include <iostream>
#include <range/v3/view/istream.hpp>
#include <range/v3/range/conversion.hpp>
int main()
{
auto vec = ranges::istream<int>(std::cin) | ranges::to_vector;
for (auto elem : vec) {
std::cout << elem << std::endl;
}
}
Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;
cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter? ";
cin >> size[ARRAY_SIZE];
cout << "Enter your number: \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> size[i];
}
cout << "\nYour numbers reversed are:\n";
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Your infinite loop is because i is unsigned, so i >= 0 is always true.
Here's a C++-ified version:
#include <iostream>
#include <vector>
int main() {
std::cout << "You may enter up to 50 integers:\n";
std::cout << "\nHow many would you like to enter? ";
int count;
std::cin >> count;
// Use a std::vector which can be extended easily
std::vector<int> numbers;
for (int i = 0; i < count; ++i) {
std::cout << "Enter your number: \n";
int v;
std::cin >> v;
// Add this number to the list
numbers.push_back(v);
}
std::cout << "\nYour numbers reversed are:\n";
// Use a reverse iterator to iterate through the list backwards
for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
// An iterator needs to be de-referenced with * to yield the value
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
std::cout << numbers[i];
}
Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.
I am trying to input data to an array and then print them by using a function but I am not sure how to organize the code.
#include <iostream>
using namespace std;
void showGrade(double grade[], int size);
int main()
{
double grade[];
int size;
for (int i = 0; i < size; i++)
{
cout << "Please enter the number of grade" << endl;
cin >> size;
}
showGrade(grade, size);
return 0;
}
void showGrade(double grade[], int size) //How many grade we have
{
for (int counter = 0; counter < size; counter++)
{
cout << "Please enter your grades: " << endl;
cin >> grade[counter];
cout << "Here are your grades: " << endl;
}
}
I Expect to see how many grades I input and then show them.
UPDATE 8/28/19
I figured out how to do it in main function successfully. But what I really want is to put them in a seperate function. My new codes have error at the function call which is type name is not allowed and expected a ')'. How do I make it work?
#include <iostream>
using namespace std;
void showGrades(double ar[], int size);
int main()
{
double ar[20];
int size;
showGrades(double ar[size], int size);
system("pause");
return 0;
}
void showGrades(double ar[], int size) {
cout << "Please enter the number of grade "; // array size
cin >> size;
cout << "Please enter your grades " << endl;
for (int i = 0; i < size; i++) {
cin >> ar[i];
}
cout << "The grades you entered are: " << endl;
for (int i = 0; i < size; i++) {
cout << ar[i] << endl;
}
}
First of all, you need to use the standard container
std::vector
instead of the double grade[];, since you want a variable-length
array as per user input.
Secondly, you are using un-initialized size variable in
for (int i = 0; i < size; i++)
hence it will be initialized with a garbage value. There you need no for-loop
A good starting would be:
#include <iostream>
#include <vector> // std::vector
void showGrade(std::vector<double>& grade)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -> pass the vector by ref, as the grades should be inseted to the it
{
// the logic
}
int main()
{
int size;
std::cout << "Please enter the number of grade" << endl;
std::cin >> size;
std::vector<double> grade;
grade.reserve(size); // reserve memory for unwanted re-allocations
showGrade(grade);
return 0;
}
I leave it to you to complete, after reading about the std::vector more.
Also, do not practice with using namespace std;. Read more:
Why is "using namespace std;" considered bad practice?
this is not a valid C++ code:
double grade[];
You can use std::vector:
std::vector<double> grade;
To insert a grade to the vector you can use grade.push_back(someGrade);
So basically I am trying to write a program which accepts an array of integers and then outputs the Max Min and smallest Mode and how many times it occurs.
I have been able to find both max and min and mode, but instead of the smallest mode my code outputs the one that occurs first. And i am not sure how to handle an input with more than one mode.
Below i’ll post my code:
#include
using namespace std;
int main() {
int p,max,min,mode;
cout << "Enter the number of postive integers:"<< endl;
cin >> p;
int pos[p];
cout << "Now enter postive integers!" <<endl;
for(int i=0; i<p; i++) {
cout << "Positive integer " << i+1 << ":";
cin >> pos[i]; }
max =pos[0];
min =pos[0];
for( int i=0; i<p; i++){
if(pos[i]> max) max=pos[i];
if(pos[i]< min) min=pos[i];
}
cout << "Max=" << max << endl;
cout << "Min=" << min << mode= pos[0];
int count[20];
int t=0;
for(int c=0;c<p; c++)
{
for(int d=0;d<p;d++)
{
if(pos[c]==pos[d])
{
count[c]++;
t++;
}
}
int modepos, maxno=count[0];
for(int e=1;e<p;e++)
{
if(maxno<count[e])
{
maxno=count[e];
modepos=e;
}
}
mode=pos[modepos];
if(t==1) {
cout << "There is no positive integer occuring more
than once." << endl;
}
else {
cout <<"The most occuring positive integer is:"<< mode;
cout << "\nIt occurs " << t << " times." << endl;
} return 0; }
there may be simpler and better ways to code this but since i’m a beginner and have only learned loops/conditionals/arrays/variable declaration etc I can only use them in the program, any help will be appreciated.
Do you learn about std::map? The algorithm for counting how many times of an element on an array is very simple with std::map
std::map<long, long > mapFreq;// first: for store value of array pos, second for store value's counter
mapFreq.insert(std::pair<long, long>(pos[0], 1));
for(int i = 1; i < dsize; i++)
{
auto &it = mapFreq.find(pos[i]);
if(it != mapFreq.end())
{
it->second++;
}
else
{
mapFreq.insert(std::pair<long, long>(pos[i], 1));
}
}
Then you can loop through map Freq for what you need:
int number, counter;
for(auto it : mapFreq)
{
if(it.second < counter)
{
number = it.first;
counter = it.second;
}
}
Maybe you can try doing this:
#include <iostream>
#include <algorithm> //for sorting
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++) cin>>a[n];
sort(a,a+n);
int b[a[n-1]];
for(int i=0;i<a[n-1];i++) b[i]=0;
for(int i=0;i<n;i++) b[a[i]]++;
cout<<"Largest number = "<<a[n-1]<<endl;
cout<<"Smallest number = "<<a[0]<<endl;
int rep=0;//repetition
int mode=0;
for (int i=0;i<a[n-1];i++){
if(b[i]>rep){
rep=b[i];// set times of repetition
mode=i;// set new mode
}
}
cout<<"Mode = "<<mode<<endl;
}
This is what I have so far...
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> list1;
vector<int> list2;
void listAdd(int n, vector<int>v) {
while (n != 0) {
v.push_back(n);
cin >> n;
}
}
void printList(vector<int>v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
}
int main() {
int nInput;
cout << "Please enter numbers for list1... (end with a '0') " << endl;
cin >> nInput;
listAdd(nInput, list1);
printList(list1);
return 0;
}
I basically want all numbers entered by the user (until they enter a 0) to be stored in the vector called list1. Then later i can call the same function to add numbers to another vector...
Help really appreciated :)
you need to pass the vectors by reference
void listAdd(int n, vector<int>& v);
void printList(vector<int>& v);