this is my first time posting on here, and I may not be doing this the right way, sorry in advance.
I am having trouble understanding how to copy two separate one dimensional arrays into one multidimensional array. It is part of my assignment, but I already turned it in and am probably going to lose points in it, but it's ok. As long as I get to understand how it's done, I'd still be happy.
The specific part I am having trouble with is section 5, I got everything else down, maybe it's because its been a long day, but I just can't seem to get it. I will post the whole assignment as well as my code. Thank you for taking the time to read all this if you did.
Write a C++ program that tests the function main and the functions discussed in parts 1 through 7. (Add additional functions, such as printing a two-dimensional array, as needed.).
Consider the following function main:
<code>int main()
{
int inStock[10][4];
int alpha[20];
int beta[20];
int gamma[4] = {11, 13, 15, 17};
int delta[10] = {3, 5, 2, 6, 10, 9, 7, 11, 1, 8};
.
.
.
}</code>
Write the definition of the function setZero that initializes any one-dimensional array of type int to 0 (alpha and beta).
Write the definition of the function inputArray that prompts the user to input 20 numbers and stores the numbers into alpha.
Write the definition of the function doubleArray that initializes the elements of beta to two times the corresponding elements in alpha. Make sure that you prevent the function from modifying the elements of alpha.
Write the definition of the function copyGamma that sets the elements of the first row of inStock from gamma and the remaining rows of inStock to three times the previous row of inStock. Make sure that
you prevent the function from modifying the elements of gamma.
5. Write the definition of the function copyAlphaBeta that stores alpha into the first five rows of inStock and beta into the last five rows of inStock. Make sure that you prevent the function from modifying the
elements of alpha and beta.
Write the definition of the function printArray that prints any one-dimensional array of type int.
Write the definition of the function setInStock that prompts the user to input the elements for the first column of inStock. The function should then set the elements in the remaining columns to two times the
corresponding element in the previous column, minus the corresponding element in delta.
Here is my code:
<code>
#include <iostream>
using namespace std;
int setZero(int alpha[], int beta[]);
int inputArray(int alpha[]);
int doubleArray(const int alpha[], int beta[]);
int copyGamma(const int gamma[], int inStock[][4]);
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize);
void printArray(int print[], int n);
int setInStock(int inStock[][4],const int delta[]);
int main()
{
int inStock[10][4];
int alpha[20];
int beta[20];
int gamma[4]={11,13,15,17};
int delta[10]={3,5,2,6,10,9,7,11,1,8};
setZero(alpha, beta);
cout << "Alpha after initialization" << endl;
printArray(alpha, 20);
inputArray(alpha);
cout << "Alpha after reading 20 numbers" << endl;
printArray(alpha, 20);
doubleArray(alpha, beta);
cout << "Beta after a call to doubleArray" << endl;
printArray(beta, 20);
copyGamma(gamma, inStock);
copyAlphaBeta(inStock, 10, alpha, beta, 20);
for (int row=0; row<10;row++)
for (int col=0; col<4; col++)
{
if (col%4==0)
cout << endl;
cout << inStock[row][col] << '\t';
}
cout << endl;
setInStock(inStock, delta);
return 0;
}
int setZero(int alpha[], int beta[])
{
for (int i=0; i<20; i++)
{
alpha[i]=0;
beta[i]=0;
}
cout << endl;
}
int inputArray(int alpha[])
{
cout << endl;
cout << "Enter 20 integers" << endl;
for (int i=0; i<20; i++)
{
cin >> alpha[i];
}
cout << endl;
return 0;
}
int doubleArray(const int alpha[], int beta[])
{
cout << endl;
for (int i=0; i<20; i++)
{
beta[i]=alpha[i]*2;
}
cout << endl;
return 0;
}
int copyGamma(const int gamma[], int inStock[][4])
{
cout << endl;
cout << "inStock after a call to copyGamma" << endl;
for (int row=0;row<10;row++)
for (int column=0;column<4;column++)
{
if (row==0)
inStock[row][column]=gamma[column];
else
inStock[row][column]=3*inStock[row-1][column];
}
cout << endl;
for (int r=0;r<10;r++)
for (int c=0; c<4;c++)
{
if (c==0)
cout << endl;
cout << inStock[r][c] << '\t';
}
cout << endl;
return 0;
}
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize)
{
cout << endl;
cout << "inStock after a call to copyAlphaBeta" << endl;
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
for (int counter=0; counter<numSize; counter++)
{
if(r<5)
{
inStock[r][c]=alpha[counter];
}
else if (r>=5)
{
inStock[r][c]=beta[counter];
}
}
}
}
cout << endl;
}
void printArray(int print[], int n)
{
cout << endl;
for (int i=0;i<n;i++)
cout << print[i] << " ";
cout << endl;
}
int setInStock(int inStock[10][4],const int delta[])
{
int input;
cout << endl;
cout << "Enter 10 integers" << endl;
for (int r=0;r<10;r++)
for (int c=0;c<4;c++)
{
if(c==0)
{
cin >> inStock[r][c];
}
else
inStock[r][c] = 2 * inStock[r][c-1] - delta[r];
}
for (int row=0; row<10;row++)
for (int col=0; col<4; col++)
{
if (col%4==0)
cout << endl;
cout << inStock[row][col] << " ";
}
}
TL;DR - Need help understanding past homework, I just want to know the proper way to do it. Also please critique, looking for ways to improve. Thank you!
Edit:
The problem I have is with this part:
Write the definition of the function copyAlphaBeta that stores alpha into the first five rows of inStock and beta into the last five rows of inStock. Make sure that you prevent the function from modifying the
elements of alpha and beta.
and my code relating to this portion of the question is:
<code>
void copyAlphaBeta(int inStock[][4], const int numberOfRows, const int
alpha[], const int beta[], int numSize)
{
cout << endl;
cout << "inStock after a call to copyAlphaBeta" << endl;
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
for (int counter=0; counter<numSize; counter++)
{
if(r<5)
{
inStock[r][c]=alpha[counter];
}
else if (r>=5)
{
inStock[r][c]=beta[counter];
}
}
}
}
cout << endl;
}</code>
Thank you for the links, I am not allowed to use vectors at the moment, but I am definitely going to study up on them.
First of all, if you're allowed to use std::vector you should use it. Read up on std::vector here for more details.
Vector provides a dynamically allocated (in the back) chunk of memory that can "expand" and change at runtime depending on adding/deleting elements. You might want to learn to use a vector as they are very useful.
However, you don't really need a vector to do your copying. You can use std::copy to do this for you. More info for it here: std::copy
You can use it to take 3 inputs for your case. First two are the beginning and end pointers, the last input is the starting pointer for the destination. You should be able to figure out what they are for your project.
In your nested for-loops, the last loop is wrong and it will repeatedly put different values of alpha[count] and beta[count] into a same inStock[r][c] element.
You can remove this loop and change the code like
for(int r=0;r<numberOfRows;r++)
{
for(int c=0;c<4;c++)
{
if(r<5)
{
inStock[r][c]=alpha[c]; // assuming size of alpha is 4
}
else if (r>=5)
{
inStock[r][c]=beta[c]; //assuming size of beta is 4
}
}
}
In this code, you have assumed inStock has 4 columns, these 4 columns of each row, are going to be filled with 4 elements of alpha and beta arrays.
Related
I'm writing two functions: one of them is for "filling" array with random values and int the second function I have to use the same array, choose one row and find the min element of that row.
But the problem is that I don't know how to pass values from one function to another.
Here is my code:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void fillarray(int arr[5][5], int rows, int cols) {
cout << "Static Array elements = \n\n" << flush;
for(int i = 0; i < rows; ++i) {
cout << "Row " << i << " ";
for(int j = 0; j < cols; ++j) {
arr[i][j] = rand() % 10;
cout << arr[i][j] << " " << flush;
}
cout << endl;
}
cout << " \n\n";
}
void minarray(int a, void fillarray) { // don't know what to write here
there:
int min = INT_MAX; // Value of INT_MAX is 2147483648.
if(a > 4) {
cout << "Invalid input! " << endl;
goto there;
}
for(int counter = 0; counter < 5; ++counter) {
if(arr[a][counter] < min) min = arr[a][counter];
}
cout << "Minimum element is " << min << endl;
}
int main() {
int z;
srand(time(NULL));
const int rows = 5;
const int cols = 5;
int arr[rows][cols];
fillarray(arr, rows, cols);
cout << "Enter the number of row: ";
cin >> z;
minarray(z, fillarray)
system("PAUSE");
}
For starters the function fillarray has redundant parameter cols because this number is known from the declaration of the first parameter int arr[5][5].
Th function can be declared like
void fillarray(int arr[5][5], int rows )
You could supply the parameter cols in case when not the whole array is filled in the function.
You already filled the array by this call
fillarray ( arr, rows, cols );
The function performed its task. So there is no need to reference the function one more time as you are trying
minarray(z, fillarray)
The function minarray can be declared either like
void minarray( const int arr[], size_t n );
and called like
minarray( arr[z], cols );
with a preliminary check that z is less than 5.
Or it can be declared like
void minarray( const int arr[][5], size_t n, size_t row );
and called like
minarray( arr, rows, z );
Pay attention to that there is the standard algorithm std::min_element that allows to find minimum element in an array. And to fill an array with values you can use the standard algorithm std::generate.
And each function should do only one task. For example the function fillarray should silently fill the array with values. To output the array you could write a separate function.
I'm not sure this even compiles, but i'm guessing you want to pass int arr[x][y] from the fill Array function to the minArray function. To do that you first need to include arr as a parameter of minArray. From there you need to pass it by reference. Then, you can call minArray from fillArray.
What you need to do is call fillarray to fill your array. So it would look like
fillarray(arr, rows, cols);
Just like you have so far. Now, you have array arr all filled in. minarray doesn't care how that happened. So don't pass it your filler method. Pass it the array.
minarray(cols, arr[z]);
You don't need to pass the entire array -- just the row in question. You're also passing the width.
And change the definition of minarray:
void minarray(int length, int[] array)
Now, your minarray itself needs changes. First, get rid of the if-check. You don't need to pass a row number now, but you do need the number of columns passed as length.
Then your for loop looks like:
for (int index = 0; index < length; ++index) {
if (array[index] < min) {
min = array[index];
}
}
So, to summarize:
Main declares the data and calls your two methods.
fillarray populates the array. It is called from main the way you already have.
minarray prints the minimum on a single line. It is also called from main, passing in the array, not the method that filled it.
You have one more issue, however. fillarray hardcodes the array size as 5x5, but main uses constants defined. I'd move those contents to the top of the file and use them in both places.
Move to the top, below any #includes:
const int rows = 5;
const int cols = 5;
Define fillarray:
void fillarray(int arr[rows][cols]) {
And when you call it from main:
fillarray(arr);
I'll let the other answers answer your question and concentrate on the code around your goto that you asked about in the comments.
In main you have this:
cout << "Enter the number of row: ";
cin >> z;
minarray(z, fillarray)
In minarray you have this:
void minarray(int a, void fillarray) { // don't know what to write here
there:
int min = INT_MAX; // Value of INT_MAX is 2147483648.
if(a > 4) {
cout << "Invalid input! " << endl;
goto there;
}
First, there's absolutely no reason to use goto. You could do this:
void minarray(int a, void fillarray) { // don't know what to write here
int min = INT_MAX; // Value of INT_MAX is 2147483648.
while(a > 4) { // loop for as long as "a > 4"
cout << "Invalid input! " << endl;
}
Removing the goto made the bug rather apparent. a will never change inside the loop, so it'll just print Invalid input! forever if you give it invalid input. An alternative would be to validate the input when you actually get the input from the user (in main):
while(true) { // loop forever
cout << "Enter the number of row: ";
if(cin >> z) { // check that the user inputs an int
if(z<0 || z>4) // validate the input
cout << "Invalid input!\n";
else
break; // we got valid input, break out of the while loop
} else { // user did not input an int
std::cout << "input failed - aborting\n";
return 1; // return from main to exit the program
}
} // if the program reaches this point, it'll ask the user for input again
// and that will only happen if the user gives it an int that is <0 or >4
I'm learning c++ and I'm trying to ask the user to input 4 numbers in a function, and then simply print the array.
int getFourNums();
int main(int argc, char** argv){
int getNums;
getNums = getFourNums();
cout << "The array is: " getNums << endl;
}
int getFourNums(){
int i;
int myArray[4];
cout << "Enter 4 nums: ";
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
return myArray[i];
As of now, it's letting me get the four numbers, but the result that's printing is "The array is: 0." I'm not quite sure why the array is seemingly not populating.
Your fundamental problem is that int getFourNums() can only return a single integer, not an array of them. The next problem is that functions cannot return raw arrays for historical reasons. Your choices are to return a std::array, a struct containing the array, pass the array by reference into the function, or return a std::vector. My preference for this application is a std::vector - it is flexible, and although not quite as efficient as std::array, you should probably default to std::vector unless you have a good reason otherwise. Your getNums code would then look like:
std::vector<int> getFourNums() {
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
int v;
cin >> v;
result.push_back(v);
}
return result;
}
To print the vector, see this question. My personal preference would be a range-based for loop over the vector; your tastes may vary.
One issue in your code is that a loop like
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
will end up with i==4. Hence, return myArray[i] will exceed array bounds and/or access an uninitialised value then and yield undefined behaviour.
The main issue, however, is that in C++ you'll follow a very different approach and use collection types like std::vector instead of plain arrays. See the following code illustrating this. Hope it helps.
#include <vector>
#include <iostream>
std::vector<int> getFourNums(){
int val;
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
cin >> val;
result.push_back(val);
}
return result;
}
int main(int argc, char** argv){
std::vector<int> fourNums = getFourNums();
for (auto i : fourNums) {
cout << i << endl;
}
}
int getFourNums() will only let you return one int, not the whole array and return myArray[i]; is out of bounds since i == 4. You can only use the range [0,3] as indices for your array. Here's a reworked version with comments in the code.
#include <iostream>
#include <vector>
// don't do "using namespace std;" since it includes
// a lot of stuff you don't need.
// Here's a function that will return a vector of int's
// It'll behave much like a C style array
// but can have variable length and you can use
// a lot of standard functions on it.
std::vector<int> getNums(size_t count) {
// The "array" we'll return with "count" number of
// default constructed int:s (they will all be 0):
std::vector<int> myArray(count);
std::cout << "Enter " << count << " nums: ";
// A range based for loop that will go through
// all int:s in "myArray". "num" will be
// a reference to each int in the vector which
// means that if you change the value of "num",
// you'll actually change the value in the vector.
for(int& num : myArray) {
// read values into the int currently
// referenced by num
std::cin >> num;
}
// return the vector by value
return myArray;
}
// Put main() last so you don't have to forward declare the functions
// it uses
int main() {
// call getNums with the value 4 to read 4 int:s
std::vector<int> Nums = getNums(4);
std::cout << "The array is:";
// print each int in the vector. There's no need to use
// a reference to the int:s here since we won't be changing
// the value in the vector and copying an int is cheap.
for(int num : Nums) {
std::cout << " " << num;
}
// std::endl is rarely good when you only want to output a newline.
// It'll flush the buffer with is costly.
// Make a habit of using "\n" in most cases.
std::cout << "\n";
}
I see that you want to return entire array but just look at your return type:
int getFourNums()
You're returning an integer right? In this situation the returned integer is always myArray[4]. Be aware that it's an integer value, you're returning something that doesn't belong to you actually!
So what to do? I suggest you to pass your array to function like this:
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
Now you filled your array. How to print your array then? We can't simply give our array name and tell cout to print it like you did (you couldn't actually!). Nothing magical here. We're going to print your array's element one by one:
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
Finally whole code looks like this:
#include <iostream>
using namespace std;
const int SIZE = 4;
void getFourNums(int myArray[]);
void printFourNumbers(int array[]);
int main(int argc, char** argv){
int myArray[SIZE];
getFourNums(myArray);
printFourNumbers(myArray);
}
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
So I'm new to C++ and am writing a program to calculate the mean, median, standard deviation, min, and max of a program. The issues I'm having are that I don't know how to correctly call functions from other files in the project, and when I try to print(c out <<) my array, it returns a weird value like 0 x 0017 c 530 (disregard the spaces). If anyone could help me correctly return these functions, and print the list correctly, I would be very grateful! Here's my code (not including the .h file):
#include <iostream>
using namespace std;
#include "stats.h"
int main()
{
double nums[10000] = {};
int n;
cout << "Enter number of values: ";
cin >> n;
for (int i = 1; i <=n; i++) {
cout << "Enter number " << i << ": ";
cin >> nums[i-1];
}
// me trying to print the nu ms list
cout << nums << endl;
// me trying to call the function
double mean(double nums[], int n);
return 0;
}
stats. cpp
#include "stats.h"
double mean(double nums[], int n)
{
double sum = 0;
double average;
for (int i = 0; i > n; i++) {
sum += nums[i];
}
average = sum / n;
return average;
}
Instead of
cout << nums << endl;
Just like you have a loop to enter one value at a time in an array, you also need a similar loop to print one value at a time from the array.
To call a function from another translation unit, you would typically declare the function in a header file, your stats.h would be an excellent candidate:
double mean(double nums[], int n);
And then just invoke it from your main:
std::cout << mean(nums, n) << std::endl;
That's it.
Also:
using namespace std;
You need to have someone help you to get an amnesia, and completely forget that C++ has anything like this. This is bad programming practice.
double mean(double nums[], int n); is declaration of function, not invoking of function. You should
double mean_value = mean(nums, n);
cout << mean_value << endl;
And cout << nums << endl; won't print out the elements of the array, just the address of the array. You need to loop the array to print out all the elements.
I am trying to figure out what I am doing wrong here and its five in the morning and I have to turn this in today at 9 in the morning, so this is my last hope to come to you guys.
This program has to allow a user to enter 5 ints, 7 floats and 5 chars, which go into arrays which have to be coded via Function Templates. The numeric data than has to be bubble sorted and averaged. This has to be printed out Then I have to save the arrays to a .dat file and retrieve the data from the file and once again output it.
Errors: The Average is not recorded properly somehow so you get a nasty random memory output.
Only the int values are being saved to the text file, and I don't even know how to retrieve properly and print the retrieved values again.
Updated Code with fixed calc function
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
//Load data to array from Keyboard.
template <class T>
void load(T *a,const int n)
{
for(int i=0;i<n;i++)
cin>>a[i];
}
//Calc and Print the Average for a numeric array.
template <class T>
void calc(T *a,const int n,float *avg)
{
float b=0;
for (int i=1;i<n;i++)
{
b+=a[i];
}
*avg=b/n;
cout<<"The Average is: "<<*avg<<endl;
//Does not work. Prints out a random block of memory.
//Tried a couple things and still get he same bug.
}
//Sort the data array in ascending order.
template <class T>
void sort(T *a,const int n)
{
float t;
for(int i=0;i<n-1;i++)
for(int j=0;j<n-1;j++)
if (a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
//Save the array data to a text file.
template <class T>
void get(T *a,const int n)
{
ofstream outfile("C:\array.dat", ios::out);
for(int i=0;i<n;i++)
outfile << a[i]<< endl;
outfile.close();
//Only saves the first array (The ints)
}
//Retrieve the array data from the text file.
template <class T>
void save(T *a,const int n)
{
ifstream infile("C:\array.dat", ios::in);
for(int i=0;i<n;i++)
{
infile>>a[i];
}
infile.close();
}
/*Output should include the average for each of the two numeric arrays
along with all three arrays being printed out in ascending order twice,
once before the text file is saved and once after the array is retrieved
from the text file*/
int main()
{
const int n1=5,n2=7,n3=5;
int a[n1];
float b[n2];
char c[n3];
float avg[3];
int i;
cout<<"Enter 5 integers"<<endl;
load(a,n1);
sort(a,n1);
calc(a,n1,avg);
cout<<"Enter 7 floats"<<endl;
load(b,n2);
sort(b,n2);
calc(b,n2,avg+1);
cout<<"Enter 5 strings"<<endl;
load(c,n3);
cin.ignore(20, '\n');
sort(c,n3);
cout << endl;
cout<<"Output:"<<endl;
cout<<"The Integer array:" << endl;
for (i = 0; i < n1; i++)
cout << a[i] << " ";
cout << endl;
cout<<"The Float array:" << endl;
for (i = 0; i < n2; i++)
cout << b[i] << " ";
cout << endl;
cout<<"The String array:" << endl;
for (i = 0; i < n3; i++)
cout << c[i] << " ";
cout << endl;
save(a,n1);
get(a,n1);
save(b,n2);
get(b,n2);
save(c,n3);
get(c,n3);
//Need to print the now returned values here.
cout << endl;
//cin.get();
system("PAUSE");
return 0;
}
Sorry if half of this doesn't make sense. I am really tired.
For the average:
template <class T>
void calc(T *a,const int n,float *avg)
{
float b=0;
for (int i=1;i<n;i++)
{
b+=a[i];
}
avg[n]=b/n;
cout<<"The Average is: "<<avg[4]<<endl;
//Does not work. Prints out a random block of memory.
//Tried a couple things and still get he same bug.
}
you don't need an array of averages, you just want one average.
agv[n] = b / n; //assigns to the the n'th elemement of an array called avg.
try this instead:
*avg = b/n
And for printing it out, just '*avg' also.
When you call calc, try:
float avg1;
calc(b,n4,&avg1);
When you see & and *, read them as the following:
& address of
* contents of address
you only need three averages, one for the 5 ints, one for the 7 floats and one for the 5 chars.
float avg[4]; // should be: float avg[3];
You seem to be passing the wrong parameters to each of the calc functions. When you call calc for the ints, use:
calc(a,n1,avg);
for floats:
calc(b,n2,avg+1);
for chars:
calc(c,n3,avg+2);
n4=2; is not relevant to anything, you can delete n4.
When you open the file, you will need to specify ios:app which appends to the existing file. Without that, every time you write to the file anything that existed in it before will be thrown away.
ios::out | ios::app
So, first write just use ios::out, after that include ios::app
Obviously I need a sum function for this and accumulate will not cut it
I need to create program - a vector - with n number of elements the user can prescribe - and the sum function can only sum POSITIVE elements even though the user can enter negative elements as well...
In the computeSum function I also need to add a "success" to the whole group
computeSum (dataVec, howMany, total, sucess);
and create a parameter for people who enter - all negative numbers but want to sum them but are unable to because there are no positive numbers
if (success) {
cout << "The sum is " << total << endl;
}
else {
cerr << "Oops, you cannot add these elements.";
}
So here is what I got
#include <iostream>
#include <vector> // need this in order to use vectors in the program
using namespace std;
int main()
{
vector<double> dataVec;
double i, n, howMany, total;
cout << "How many numbers would you like to put into the vector?";
cin >> n;
dataVec.resize(n);
for(vector<double>::size_type i=0;i < n;i++)
{
cout << "Enter the numbers: \n";
cin >> dataVec[i];
}
cout << "How many POSITIVE numbers would you like to sum?";
cin >> howMany;
cout << computeSum (dataVec, howMany, total);
}
double computeSum (vector<double> &Vec, howMany, total)
{
double total =0;
for(int i=0;i < howMany;i++)
total+=Vec[i];
return total;
}
I also seem to having trouble compiling just this - computeSum() is not being understood in int main(); howMany is not being understood in computerSum(); and on a gloabl scope total() and howMany() are undeclared (I guess that would mean i would need to decalre globally???)
In fact, accumulate will “cut it”, with an appropriate functor that only regards positive values:
int sum_positive(int first, int second) {
return first + (second > 0 ? second : 0);
}
…
std::accumulate(data.begin(), data.begin() + how_many, 0, sum_positive);
Getting on my hobby horse: Boost Range Adaptors. Hits the sweet point with me
#include <boost/range/adaptors.hpp>
#include <boost/range/numeric.hpp>
bool isnatural(int i) { return i>=0; }
using namespace boost::adaptors;
int main(int argc, char** args)
{
static const int data[] = { -130, -1543, 4018, 5542, -4389, 15266, };
std::cout << "sum: " << boost::accumulate(data | filtered(isnatural), 0) << std::endl;
return 0;
}
Output:
sum: 24826
With C++11 awesomeness1 spice:
std::cout << "sum: " << boost::accumulate(data
| filtered([] (int i) { return i>=0; }), 0) << std::endl;
1: to be honest, I really hate the clumsyness of lambda syntax:
having to specify the parameter type always
having to spell out the return statement to
For this scenario, it seems to that filtered([] (i) { i>=0 })
could be figured out by the compiler. Well, perhaps in c++22 :)
Your computeSum() function must appear above your main() function in the source file for it to be in scope. Also in your computeSum() function signature you haven't given types to the howMany and total variables. I'm guessing they should be double howMany and double total?