Ok so, all the numbers being passed into this function as parameters, are returning correct values, I cant figure out why after i run this i get some ridiculous number as the standard deviation. i.e the number i get is (4.23947e10) or something along those lines, and the display function is skipping every other line.
float stdDev(int arrayList [], int count, float average)
{
int deviation;
int sum2 = 0;
for (int i = 0; i <= count; i++)
{
sum2 += pow((arrayList[i] - average), 2);
}
deviation = sqrt(sum2 / (count - 1));
return deviation;
}
void displayList(int heightlist [], int weightlist[], int count)
//displays list of integers based on lists
{
cout << "\tHeight(s)" << " " << "Weight(s)" << endl;
for (int i = 0; i <= count; i++)
{
cout << "\t[" << heightlist[i] << "]" << " " << "["<< weightlist[i] <<"]" << '\n';
i++;
}
}
I think you're going one too far:
for (int i = 0; i <= count; i++)
// ^^
Probably meant i < count.
Also:
int deviation;
int sum2 = 0;
You mean float deviation, sum2?
Related
I am doing a code on tracking how much food tigers eat in 1 week and I am tracking 3 tigers.
I am supposed to print average, maximum and minimum. Whenever I run the code it doesn't print the max or minimum, only the initialized values I have in the function. I am assuming the int main() ignores my return values completely, but I can't see why is that. I have done many functions before and I do the same code every time and call it in main
Here is the code:
int main(){
cout << "Enter whether you want to find minimum for tiger 1 2 or 3. (Please
only enter 0, 1 or 2): ";
cin >> temp;
if (temp < 0) {
cout << "CAN'T RUN NEGATIVE NUMBERS";
exit(2);
}
least(food, temp, minimum);
cout << "\n";
cout << "The Tiger " << temp << " has minimum: " << minimum << " ";
cout << "\n \n ";
}
float least(float food[][DAYS], int temp, float min) //loop for days only
{
minimum = food[0][0];
//temp has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (min<food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return max;
}
system("PAUSE");
return 0;
}
Since you are not using the return value, use the max and min argument as reference variable in your function definitions. Also the comparison in least & Most functions seems to be wrong. It should be the opposite way.
float least(float food[][DAYS], int temp, float &min) //loop for days only
{
min = food[0][0]; //temp has to be les
for (int j = 0; j < DAYS; ++j) {
if (min>food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return min;
}
float Most(float food[][DAYS], int amb, float &max) //loop for days only
{
max = food[0][0];
//amb has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (max<food[amb][j]) {
max = food[amb][j];
}
}
cout << max << " ";
return max;
}
You do not use your methods' return values. Replace
Most(food, amb, maximum);
and
least(food, temp, minimum);
with
maximum = Most(food, amb, maximum);
and
minimum = least(food, temp, minimum);
So I need to create a function to find the sum of rows in my 2D array. Array is fixed, matrix[5][5], and user inputs 25 integers.
I know how to find the sum of my rows using the following code:
//for sake of ease lets say user inputs numbers 1-25
for (r = 0; r < 5; r++)
{
for (c = 0; c < 5; c++)
{
sum = sum + matrix[r][c]
}
cout << "\n" << sum;
sum = 0;
}
//the code above will display the sum of each row as follows:
15
40
65
90
115
I want to display the totals for each row as
Row 1:
Sum =
Row 2:
Sum =
etc...
How do I pass the array to a function in order to find the sum of each row and how do I separate the individual sum of rows to display like I want?
I have read a chapter on passing multidimensional arrays to functions like 4 times over in a c++ beginners book, I have read and looked at many different forums online and maybe it is because I have been starring at it for too long I am not seeing the answer but I have given myself a headache. I really just want to understand how to pass it. I have tried to modify the passing of an array to a function to find the sum of all the integers in the array but I could not get it to work for what I needed.
ETA(10/7/2017 1535 PCT):
So I am trying the following to try and pass my 2D array to a function and calculate the sum...
void total(int matrix[][5], int n, int m)
{ // I am getting an error here though that states "expected a ';' "
for (r = 0; r < n; r++)
{
int sum = 0;
for (c = 0; c < m; c++)
sum += matrix[r][c];
}
cout << "Row " << r << " = " << sum << endl;
}
Is this even how you create a function with a 2D array?
ETA (10/7/2017 2100 PCT)
So I think I figured out how to pass the array, but I cannot seem to get it to do the proper math, meaning this does not sum up the rows....
#include "stdafx.h"
#include "iostream"
using namespace std;
int total( const int [][5], int, int);
int main()
{
int c, r, matrix[5][5];
cout << "Please input any 25 numbers you'd like, seperated by a space, then press enter:" << endl;
for (r = 0; r < 5; r++)
{
for (c = 0; c < 5; c++)
{
cin >> matrix[r][c];
}
}
getchar();
cout << endl << "Matrix: " << endl;
for (r = 0; r < 5; r++)
{
cout << endl;
for (c = 0; c < 5; c++)
{
cout << matrix[r][c] << "\t";
}
cout << endl;
}
cout << "Please press the enter key to get the sums of each row << endl;
getchar();
cout << "Sum = " << total << endl; //this displays "Sum = 013513F2"
system("PAUSE");
}
int total(const int matrix[][5], int R, int C)
{
int sum = 0;
for (int r = 0; r < R; r++)
{
for (int c = 0; c < C; c++)
{
sum = sum + matrix[r][c];
}
}
return sum;
}
Passing an array of any dimension can be done by using the syntax: type (&name)[numElements] by reference. Or by pointer you would replace the & with a *. Below is a basic example that compiles, which passes the array by reference to the pass2Darray function. Alternatively, you could simply use a regular array with size [5 * 5] to ensure that it's entirely contiguous. Since a 2D array is not natively something that exists in C++. And then, since you're working with matrices, you can access it in column major by [row * i + col] or in row major by [col * j + row].
#include <iostream>
// Reference to multiArray
// int (&someName)[num][num]
// Pointer to multiArray
// int (*someName)[num][num]
void pass2Darray(int (&passed)[1][1]) {
std::cout << passed[0][0];
}
int main() {
int arr[1][1] = { {1} };
pass2Darray(arr);
return 0;
}
Just to help the future readers this is what I came up with. Took a lot of research and a million different trial and errors but here it is:
int math(int a[5]) //The function the array has been passed to
{
//Declaring the variables in the function
int sum = 0;
double average = 0;
int min = 0;
int max = 0;
min = a[0]; //setting the minimum value to compare to
for (int C = 0; C < 5; C++) //Creates the loop to go through the row elements
{
sum = sum + a[C]; // calculates the sum of each row
if (a[C] < min) min = a[C]; //assigns the element of lowest value from row
if (a[C] > max) max = a[C]; //assigns the element of highest value from row
}
average = sum / 5; //calculates the average of each row
cout << "Sum = " << sum << endl; //Outputs sum
cout << "Average = " << average << endl; //Outputs average
cout << "Min = " << min << endl; //Outputs min
cout << "Max = " << max << endl; //Oututs max
cout << endl;
return 0; //return value for function
}
Down the line that calls the function and displays the output I was looking for:
for (r = 0; r < 5; r++) //sets up row loop for display
{
cout << "Row " << r+1 << ":" << endl;
math(matrix[r]); //displays calculations done in math function
cout << endl;
}
Hope this helps someone down the road...
I wrote a program to accept 15 integer values in an array, then pass this array to a function which will multiply each even index value by 4.
Currently the program displays the initial array, but seems like it's getting hung up before it displays the modified array.
Please help me understand why the program is getting stuck here!
int main(){
const int SIZE = 15;
int quad[SIZE] = {};
void quadruple(int[], const int);
cout << "Enter 15 integer values into an array." << endl;
for (int i = 0; i < SIZE; i++) // Accept 15 int values
{
cout << i << ": ";
cin >> quad[i];
}
cout << "Before quadruple function is called: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
quadruple(quad, SIZE);
cout << "After even index value multiplication: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
return 0;
}
void quadruple(int values[], const int SZ){
for (int i = 0; i < SZ; i + 2) // Multiply even values by 4
{
if ((i % 2) == 0)
{
values[i] = values[i] * 4;
}
else // Keep odd values the same
{
values[i] = values[i] * 1;
}
}
}
for (int i = 0; i < SZ; i + 2)
"i + 2" doesn't do anything.
You probably meant "i += 2;".
Your homework assignment is to find some documentation about your system's debugger. And find where your rubber duck is, as it's been suggested in the comments.
Why do I get a program crash for large values but not small values for my program? If I input 1-3 the program does what it is supposed to but when I enter a number greater than that the program crashes and/or does not complete? Is it something to do with a pointer error or the way I've referenced something? I'm unsure so any help is appreciated. Thanks!
Code:
#include <iostream>
using namespace std;
void getData (int size, int *Arr){
cout << "\n\nEnter integer data one line at a time\n" << endl ;
for (int i=0; i < size; i++){
cin >> Arr[i];
}
}
void findMinAndMax(int array[], int size, int *min, int *max) {
int smallest = array[0];
int largest = array[0];
*min = smallest;
*max = largest;
for (int i = 1; i < size; i++)
{
if (array[i] > *max){
*max = array[i];
cout << "Max Value (loop): " << *max << endl;
}
if (array[i] < *min){
*min = array[i];
cout << "Min Value (loop): " << *max << endl;
}
}
// testing code
cout << "Min Value: " << *min << endl;
cout << "Max Value: " << *max << endl;
}
int *makeFrequency (int data[], int dSize, int *minDataValue, int *maxDataValue) {
cout << "Min Value Pre: " << *minDataValue << endl;// testing code
cout << "Max Value Pre: " << *maxDataValue << endl;// testing code
findMinAndMax(data, dSize, minDataValue, maxDataValue);
cout << "Min Value Post: " << *minDataValue << endl; // testing code
cout << "Max Value Post: " << *maxDataValue << endl;// testing code
int fSize = *minDataValue + *maxDataValue;
cout << "fSize: " << fSize << endl; // testing code
int *frequency;
frequency = new int [fSize];
// if frequency is 0, end
if (frequency == 0)
{
return 0;
}
// set all elements to 0 in array frequency
for (int i = 0; i <= fSize; i++) {
frequency[i] = 0;
}
for (int i = 0; i <= dSize; i++) {
int j = data[i] - (*minDataValue) + 1;
frequency[j] = frequency[j] + 1;
}
return frequency;
}
void makeHistogram (int *freq, int min, int max ){
cout << "Frequency Value HISTOGRAM: " << *freq << endl;
cout << "\n\n\n ----------- Histogram ----------------\n" << endl;
int size = min + max;
cout << "Size Value HISTOGRAM: " << size << endl;
for (int i = 0; i < size; i++){
if (freq[i] > 0) {
cout << "\n" << min + i - 1 << ": ";
for (int j = 0; j < freq[i]; j++) {
cout << '*';
}
}
}
cout << endl << endl;
}
int main() {
int dSize;
int *ArrayOfInts;
cout << "How many data values? ";
cin >> dSize;
ArrayOfInts = new int [dSize];
getData(dSize, ArrayOfInts);
int *frequency, min, max;
frequency = makeFrequency(ArrayOfInts, dSize, &min, &max);
if (frequency == 0) return -1;
cout << "Min Value MAIN: " << min << endl; // testing code
cout << "Max Value MAIN: " << max << endl; // testing code
cout << "Frequency Value MAIN: " << *frequency << endl;
makeHistogram(frequency, min, max);
delete [] frequency;
return 0;
}
One place where you have undefined behaviour which can cause crashes:
here you allocate fSize elements:
frequency = new int [fSize];
later you iterate it until fSize:
for (int i = 0; i <= fSize; i++) {
you should change to i < fSize, because there is no fSize element in your array. And the same problem with i <= dSize later on. Should be i < dSize.
btw. I dont see why only large values should cause crashes in your code, maybe this is just UB.
You're setting fSize incorrectly. It should be the difference between the maximum and minimum values, not the sum of them. Otherwise, if you have negative numbers in your list, the frequency array will be too small. And if absolute value of any of the negative numbers is larger than the highest number, fSize will be negative, which is not valid for the size of an array.
Then you need to add 1 to include both endpoints. So it should be:
int fSize = *maxDataValue - *minDataValue + 1;
Then, as the other answer pointed out, you need to fix your for loops. When the size of an array is N, the array indexes from from 0 to N-1. So it should be:
for (int i = 0; i < fSize; i++) {
using < as the loop test, not <=. If you try to write outside an array, you invoke undefined behavior, so anything can happen -- if you're lucky you get a crash, but that's not guaranteed.
You have a similar problem when you assign to frequency:
for (int i = 0; i <= dSize; i++) {
int j = data[i] - (*minDataValue) + 1;
frequency[j] = frequency[j] + 1;
}
There's no need to add 1 when subtracting *minDataValue, and doing so will cause you to go outside the array when data[i] is the maximum.
The assignment is Design and Develop a C++ program to list the first N terms of the Fibonacci series.
The output should look like this:
N=2 1,1
N=2 1,1
N=3 1,1,2
N=4 1,1,2,3
N=5 1,2,3,5
N=6 ....
My problem is that I have written the recursive function below but I'm not sure how to format it so it outputs to screen in the manner above.
#include <iostream>
using namespace std;
//Function Prototype
int fib(int);
int main()
{
for (int x = 0; x < 15; x++)
cout << fib(x) << " ";
cin.get();
cin.get();
return 0;
}
//Definition of fib
int fib(int n)
{
//Return 1 when n is 0
if ( n <= 0 )
return 0;
else if (n == 1)
return 1;
else
return fib(n-1) + fib(n-2);
}
Could someone shed some light on how to get this accomplished?
Thank you.
if you don't care too much about efficiency, a double loop will do
for (int x = 2; x < 15; x++) {
cout << "N = " << x << " ";
for (int y = 2; y <= x; y++)
cout << fib(y) << " ";
cout << endl;
}
How to format?
You have a good start.
Try this as a next step...
for (int x = 0; x < 15; x++)
cout << x << "=" << fib(x) << " " << std::endl;
cin.get();
In my system, I can add to the cout line, compile, and review the output in < 10 seconds. Fast turn around and practice (for you) are your friends.
I would take a different approach. I'd save the already computed Fibonacci values so they are not computed them over and over again, like in a map, and than using that map to print the values.
std::map<int, int> fibs;
int fib(int const n)
{
auto p = fibs.find(n);
if(p != fibs.end())
return p->second;
int f = 1;
if (n > 1)
{
f = fib(n-1) + fib(n-2);
}
fibs[n] = f;
return f;
}
You can then loop through the computed values like this:
for(int n = 0; n < 10; ++n)
{
fib(n);
std::cout << "N=" << n << " ";
for(int i = 0; i <= n; ++i)
std::cout << fibs[i] << ",";
std::cout << std::endl;
}
Since it all does is print the fibonacci number, and the ones before, you just need to add them to your output ...
You can either have an aggregating string that you pass along, that will hold all the temp values, or just call another method that will have temp outputs. (mind you, it's not very efficient though :)
int fib_verbose(int n)
{
//Return 1 when n is 0
if ( n <= 0 )
return 0;
else if (n == 1) {
return 1;
}
else {
int smaller = fib(n-2);
int larger = fib(n-1);
cout << smaller << " " << larger << endl;
return smaller + larger;
}
}
You'll have to sort out the spaces, and formatting, but that's the gist.
Edit:
As per agbinfo comment: removed the 1 printing, and also storing the variables so we don't need to call them twice. (Still, for efficiency, look at Marius's answer :) ).
Here's an example that doesn't recompute values when calling fib for a single value. You can combine Marius's idea to compute the values once even on multiple runs.
The trick is that fib(unsigned&, unsigned) will return the previous fibonacci it has already computed.
#include <iostream>
using namespace std;
unsigned fib(unsigned& m, unsigned n)
{
if (n==0) {
return 0;
}
if (n==1) {
m = 0;
// cout << "0,"; // uncomment if sequence should start with a 0
return 1;
}
unsigned prev;
m = fib(prev, n-1);
cout << m << ",";
return m+prev;
}
unsigned fib(unsigned n) {
unsigned prev;
unsigned f = fib(prev, n);
cout << f;
return f;
}
int main() {
for (unsigned i=2; i<13; i++) {
cout << "N=" << i << " ";
fib(i);
cout << endl;
}
return 0;
}
Will printout:
N=2 1,1
N=3 1,1,2
N=4 1,1,2,3
N=5 1,1,2,3,5
N=6 1,1,2,3,5,8
N=7 1,1,2,3,5,8,13
N=8 1,1,2,3,5,8,13,21