I'm trying to break this problem into function, but my problem is that I always get different sum, positive and negative count when I print out the result.
Can someone give me a hint?
Write a program that reads ten integer numbers and outputs the sum of all the positive numbers among them. The program should ignore all numbers which are less than or equal to 0. The program should also display count of positive numbers and count of negative numbers or zero.
#include <iostream>
using namespace std;
void input(int number, int positiveCount, int negativeCount, int sum);
void output(int positiveCount, int negativeCount, int sum);
int main()
{
int number, positiveCount, negativeCount, sum;
input(number, positiveCount, negativeCount, sum);
output(positiveCount, negativeCount, sum);
return 0;
}
void input(int number, int positiveCount, int negativeCount, int sum)
{
cout << "Enter 10 integers: " << endl;
for (int i = 0; i < 10; i++)
{
cin >> number;
if (number > 0)
{
positiveCount++;
sum = sum + number;
}
else
{
negativeCount++;
}
}
}
void output(int positiveCount, int negativeCount, int sum)
{
cout << sum << endl;
cout << positiveCount << endl;
cout << negativeCount << endl;
}
Your input() function needs to take its arguments by reference so it can modify them. And you need to initialize all those ints to 0 at the start or they contain garbage.
The operations you have done inside input() function is lost because the scope of the variables are only inside the function.
You need to use either pointers or reference while passing the parameters into the input() function so as not to use a local copy.
While using pointers you need to do dereferencing also.
And initialize the variable to 0 before passing to the function.
Because there is serious mistake in your program. You define four local variables in function main() and send them by value when invoking function input(). This function DO NOT modify variables defined in the function main(). It simply modify their copies. These copies is deleted when you're out of function input().
In order to modify them you should use reference:
void input(int &number, int &positiveCount, int &negativeCount, int &sum);
But it has no meaning to create four integers in function main() and to send them in the functions input() and output(). You can create four local variables in input() and then print them in this function. Then you shouldn't define function output() and you can delete it in your code. I.e. you should modify your program.
In your assignment there is written:
Write a program that reads ten integer numbers and outputs the sum of
all the positive numbers among them
So there is no need to write separate functions for this simple program. It can look like
#include <iostream>
int main()
{
const size_t N = 10;
std::cout << "Enter " << N << " integers: ";
size_t i = 0, count = 0;
long long sum = 0;
int num;
for ( ; i < N && std::cin >> num; i++ )
{
if ( num > 0 )
{
sum += num;
++count;
}
}
std::cout << "You have entered " << count << " positive numbers\n"
<< "and " << i - count << " negative numbers or seroes\n"
<< "Sum of positive numbers is " << sum << std::endl;
return 0;
}
If you want to write separate functions then for example function input could be declared as
long long input( size_t &positive_count, size_t &negative_count );
or
long long input( size_t &total_count, size_t &positive_count );
or
long long input( size_t *positive_count, size_t *negative_count );
or
long long input( size_t *total_count, size_t *positive_count );
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
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 need to make a program with three functions.
The main function should call the second function passing it the array as the first argument and the number of elements in the array as the second argument.
The second function is passed in an array and the number of elements in the array. The function should get 8 names from the user and return the number of names read back to main. Use the return statement to do this.
After the array is filled by the second function, main should then call a third function passing it the array as the first argument and the value returned by the second function as the second argument.
The third function should display the names from the array on separate lines on the computer screen. The third function is passed in an array as the first parameter. The second parameter is the number of elements in the array to be displayed.
The main function has an array of 10 elements. The second function is passed that array of 10 elements but only reads in 8 elements. The number read in by the second function is returned back to main. Main then passes the array and the value returned back from the second function to the third function.
My code up to this point is:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// get the names and store them in the array
int const arraySize(10);
int names = 8;
string array[arraySize];
// send to second function
recievenames(array, arraySize);
// send to third function
displaynames(array, 8);
return 0;
}
int recievenames(string array[], int arraySize)
{
int names = 0;
// Get names.
for (int count = 0; count < 8; count++)
{
cout << "Enter name " << (count + 1) << " of 8: ";
cin >> array[count];
if (count < 8)
{
names++;
}
}
// Display amount of names entered.
cout << names << " received.";
}
void displaynames(string array[], int names)
{
// Display names entered in array.
for (int count = 0; count < names; count++)
{
cout << array[count] << endl;
}
}
For some reason it isn't working can someone tell me why?
you have to do a foward declartion of the function prototypes recievenames() and displaynames() and place them before main() . Then you can define and embody the functions after main.
#include <iostream>
#include <string>
using namespace std;
// declare function prototypes
int recievenames(string array[], int arraySize);
void displaynames(string array[], int names);
int main()
{
// get the names and store them in the array
int const arraySize(10);
int names = 8;
string array[arraySize];
// send to second function
recievenames(array, arraySize);
// send to third function
displaynames(array, 8);
return 0;
}
//define functions
int recievenames(string array[], int arraySize)
{
int names = 0;
// Get names.
for (int count = 0; count < 8; count++)
{
cout << "Enter name " << (count + 1) << " of 8: ";
cin >> array[count];
if (count < 8)
{
names++;
}
return 0;
}
// Display amount of names entered.
cout << names << " received.";
}
void displaynames(string array[], int names)
{
// Display names entered in array.
for (int count = 0; count < names; count++)
{
cout << array[count] << endl;
}
}
I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
EDIT:
"Improved" code:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}
When you get to the 47th value, the numbers go out of int range. The maximum int value is 2,147,483,647 and the 46th number is just below at 1,836,311,903. The 47th number exceeds the maximum with 2,971,215,073.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for loop that you have. Vectors start with 0, and so by having number<=length; the range+1 element will be called. The range only goes up to length-1.
You are encountering integer overflow, meaning that you are trying to calculate a number that is outsize of the bounds of INT_MAX and INT_MIN. In the case of an unsigned number, it just overflows to zero and starts over, while in the case of a signed integer, it rolls over to INT_MIN. In both cases this is referred to as integer overflow or integer wraparound.
You could put a band-aid on the solution by using long long int (likely 64-bits on most modern systems) instead of int for your primitive data type, or you could use a better approach like a library that supports (almost) arbitrarily long data types, like libBigInteger.
References
Integer Overflow, Accessed 2014-03-04, <http://en.wikipedia.org/wiki/Integer_overflow>
C++ Big Integer Library, Accessed 2014-03-04, <https://mattmccutchen.net/bigint/>
The limits.h Header File, Accessed 2014-03-04, <http://tigcc.ticalc.org/doc/limits.html>
This is my solution to calculating BIG fibonacci numbers
// Study for algorithm that counts n:th fibonacci number
#include <iostream>
#include <cstdlib>
#include "boost/multiprecision/cpp_int.hpp"
#define get_buffer(a) buffer[(a)%2]
#define BIG boost::multiprecision::cpp_int
int main(int argc, const char* argv[])
{
// atoi returns 0 if not integer
if(argc != 2 || atoi(argv[1]) < 1){
std::cout << "You must provide one argument. Integer > 0" << std::endl;
return EXIT_SUCCESS;
}
// ring buffer to store previous two fibonacci number, index it with [i%2]
// use defined function get_buffer(i), it will do the magic for you
BIG buffer[2]={ 1, 1 };
// n:th Fibonacci
unsigned int fn = atoi(argv[1]);
// count loop is used if seeked fibonacci number is gt 2
if(fn > 2){
for(unsigned int i = 2; i < fn; ++i){
get_buffer(i) = get_buffer(i-1) + get_buffer(i-2);
// get_buffer(i-1) + get_buffer(i-2) == buffer[0] + buffer[1]
// if you want to print out every result, do it here
}
}
// Result will be send to cout
std::cout << "Fibonacci[" << fn << "] is " << get_buffer(fn-1) << std::endl;
return EXIT_SUCCESS;
}
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?