Loop in function running more than it needs to - c++

In a problem i am working on i have a function that checks if the number of spherical and cylindrical holes in rectangular block are greater than zero. In this problem i have to call the function twice. My problem is that the first time i call the function 'HoleCheck' is is running twice and assuming that zero is entered in for the cylindrical holes and makes me re-enter the value for spherical holes. How can i make it to only run once for the spherical hole check?
#include <iostream>
#include <string>
using namespace std;
void Check(double arr1[], string arr2[]);
void HoleCheck(int arr3[], string arr4[]);
int main()
{
double DimArray[3];
string MyArray[3] = { "Height", "Length", "Width"};
int totalholes[2];
string holes[2] = { "Spherical", "cylindrical"};
cout << "Enter the height, length and width of rectangle in centimeters: ";
cin >> DimArray[0] >> DimArray[1] >> DimArray[2];
Check(DimArray, MyArray);
cout << "How many spherical bubbles are present? ";
cin >> totalholes[0];
HoleCheck(totalholes, holes);
cout << "How many cylindrical holes are present? ";
cin >> totalholes[1];
HoleCheck(totalholes, holes);
return 0;
}
void Check(double arr1[], string arr2[])
{
int i;
for (i = 0; i < 3; i++)
{
while (arr1[i] <= 0)
{
cout << "Your entered " << arr2[i] << " is less than zero!\n";
cout << "Please re-enter a valid number --> ";
cin >> arr1[i];
}
}
}
void Check(double arr1[], string arr2[])
{
int z;
for (z = 0; z < 2; z++)
{
while (arr3[z] <= 0)
{
cout << "The number of " << arr4[z] << " holes must be greater than 0.\n";
cout << "Please re-enter a valid number --> ";
cin >> arr3[z];
}
}
}

Assuming that your second Check function is actually HoleCheck and that was a typo:
Your HoleCheck Function checks both elements of its arr3, but you are calling it before you enter any values into totalHoles[1].
Either just remove the first call to HoleCheck or change it so you can tell it which entry in the array to check.

Related

How to print product of all inputted numbers using a loop?

int main() {
cout << "Enter some numbers fam! " << endl;
cout << "If you wanna quit, just press q" << endl;
int n{ 0 };
int product = 1;
char quit = 'q';
while (n != 'q') {
cin >> n;
product = product* n;
cout <<"The product is : " << product << endl;
}
cout << endl;
cout << product;
return 0;
}
Whenever I print it out and cut the code using 'q', it prints me an infinite amount of "The product is 0". Also, how can I print out the final product of all numbers at the end?
So, there are some problems in your code.
First, you are taking input and assigning it to an int, which might not have been a problem, but you are also comparing the int to a char(which will cause problems in your case)
int n{ 0 };
while(n != 'q') {
cin >> n;
}
To solve that, you can make the n a string and then convert it into an integer with stoi(n) to use with the calculation
string n; // don't need to initialize a string, they are initialized by default.
int product = 1;
cin >> n; // Taking input before comparing the results
while(n != "q") { // Had to make q a string to be able to compare with n
product *= stoi(n); // Short for product = product * stoi(n)
cout <<"The product is : " << product << endl;
cin >> n; // Taking input for the next loop round
}
cout << endl;
cout << product;

Trying to find the lowest number in my array, used the same line for highest number

Basically what I am trying to do is get the lowest number, but the program is feeding me back garbage, but I use the same line of code to get the highest value, only change I made was > to <, the program gives me back the highest value no problem put not the lowest. And I have tried everything I can think of from making the lowest= x[0], lowest=101( user is suppose to enter in grades on scale of 0-100, thought made it had something to do with the value. ) and lowest =highest and it still give me back a number like -9.255596e...., any help or suggestion or greatly appreciated, or maybe a point in the right direction just really trying to understand why it works for one set of numbers and not the others.
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
double average(double,int);
double sum1(double[],int);
double highest(double[], int);
double lowest(double[], int);
int _tmain(int argc, _TCHAR* argv[])
{
double gradeBook[1000];
char x;
int count = 0;
cout << "Do you wish to start the program if so enter y to stop enter q" << endl;
cin >> x;
while (x != 'q')
{
cout << "Enter in test grade on a scale of 0 to 100" << endl;
cin >> gradeBook[count];
if (gradeBook[count]<0 || gradeBook[count]>100)
{
cout << " Please try again ";
count--;
}
else
cout << "valid answer" << endl;
count++;
cout << "Do you wish to continue entering in grades? If so enter y to stop enter q" << endl;
cin >> x;
}
highest(gradeBook, count);
cout << "The highest grade enter is " << highest(gradeBook, count) << endl;
lowest(gradeBook, count);
cout << "The lowest grade enter is " << lowest(gradeBook, count) << endl;
cout << lowest <<endl;
return 0;
}
double highest(double x[], int y)
{
double highest = 0;
for (int i = 0; i<= y; i++)
{
if (x[i]>highest)
highest = x[i];
}
return highest;
}
double lowest(double x[], int y)
{
double lowest = 100;
for (int i = 0; i<= y; i++)
{
if (x[i]< lowest)
lowest = x[i];
}
return lowest;
}
A way to resolve your question is to use code already tested.
In your case you can use min_element and max_element to find min and max element of your code:
cout << "The highest grade enter is " << *max_element(gradeBook,
gradeBook+count) << endl;

C++ swap function with array of records

I have just started to learn C++ and have been working on a few problems to hone my skills. Currently I am having a problem swapping some values of my array of records. The input validation works fine but then when I try to swap the values around the program stops responding and crashes. Here is how I have created it:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int grandprixnum;
struct DriverData {
string driver;
int car;
string team;
int grid;
int points;
};
DriverData * grand = new DriverData[grandprixnum];
int input()
{
cout << "How many drivers where there? ";
cin >> grandprixnum;
cin.sync();
DriverData * grand = new DriverData[grandprixnum];
for (int i=0; i<grandprixnum; i++)
{
cout << "Driver numbers: "<< i+1 << " \n";
cout << "What is the drivers name? \n";
getline (cin, grand[i].driver);
cin.sync();
cout << "What is the drivers car number? \n";
cin >> grand[i].car;
while (grand[i].car > 99 || grand[i].car < 1)
{
cout << "Please enter a value between 1 and 99! \n";
cin >> grand[i].car;
}
cin.sync();
cout << "What team is the driver racing for? \n";
getline (cin, grand[i].team);
cin.sync();
cout << "What grid are they in? \n";
cin >> grand[i].grid;
cin.sync();
while (grand[i].grid < 0 || grand[i].grid > 22)
{
cout << "Please enter a grid number between 1 and 22! \n";
cin >> grand[i].grid;
}
cin.sync();
cout << "What are their total points? \n";
cin >> grand[i].points;
cin.sync();
while (grand[i].points > 25 || grand[i].points < 0)
{
cout << "Please enter the drivers points between 0 and 25! \n";
cin >> grand[i].points;
}
}
}
int sorting ()
//This part _______________________________
{
for(int a=1; a<=grandprixnum; a++)
{
for(int b=0; b<=grandprixnum; b++)
{
if(grand[b].points < grand[b+1].points)
{
swap(grand[b].driver, grand[b+1].driver);
swap(grand[b].car, grand[b+1].car);
swap(grand[b].team, grand[b+1].team);
swap(grand[b].grid, grand[b+1].grid);
swap(grand[b].points, grand[b+1].points);
}
}
}
}
//To here_________________________________
int showtable ()
{
cout << "Driver Car Team Grid Points \n";
for(int c=0; c<grandprixnum; c++)
{
cout << grand[c].driver << grand[c].car << grand[c].team << grand[c].grid << grand[c].points << "\n";
}
}
int main()
{
input ();
sorting ();
showtable ();
}
I have looked around and cannot find an example or someone having the same problem as me. If someone could show me what is wrong with it. Thank you in advance.
EDIT: I have tested the swap before and it does work but it seems to struggle with the array of records.
You access to your array out of bounds. Your array has a length of grandprixnum so you can access to elments from 0 to grandprixnum-1
for(int a=1; a < grandprixnum; a++)
// ^
{
for(int b=0; b < grandprixnum-1; b++)
// ^ ^^ -1 because of b+1
{
if(grand[b].points < grand[b+1].points)
{
...
}
}
}
If ter is nothing to return in a function you dont need a return type. Use void sorting(), void input(), void showtable()
You declareted your array grand twice. On time global and second time local in function input. Declare it global and allocate it in function input.
DriverData * grand = NULL;
int input()
{
...
grand = new DriverData[grandprixnum];
Remove equal sign from this line:
for(int b=0; b<=grandprixnum; b++)
So it will be like this:
for(int b=0; b<grandprixnum; b++)
And replace this line
DriverData * grand = new DriverData[grandprixnum];
with
grand = new DriverData[grandprixnum]; // will store in global variable

I need to ask user to input a value for the triangle and a character for it?

I am almost done with the code i just need to figure out how to make the user input values for character and the height of the triangle using cout and cin thanks this is all my code hard coded.
I feel like i worded it wrong basically the program is supposed to draw a triangle using the function drawline i created below, when i compile and run it asks me to enter a user choice if i enter 1 it runs the code in the if (userChoice == 1){} basically i want a cin and cout code structure that allows them to input their values for lineLength and displayChar.
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
void drawLine (int lineLength, char displayChar);
void placePoint (int lineLength) ;
int main()
{
int userChoice = 0;
cout << "**********************************" << endl;
cout << "* 1 - DrawTriangle *" << endl;
cout << "* 2 - Plot Sine graph *" << endl;
cout << "* 3 - Exit *" << endl;
cout << "Enter a selection, please: " << endl;
cin >> userChoice;
int x,y,t =0;
char displayChar = ' ';
int lineLength = 0;
double sinVal= 0.00;
double rad = 0.00;
int plotPoint = 0;
if (userChoice == 1)
for (int x=1; x <= lineLength; x=x+1) {
drawLine ( x, displayChar);
}//end for
for (int y=lineLength-1; y >= 1; y=y-1) {
drawLine ( y, displayChar );
}//end for
}//end main at this point.
void drawLine (int lineLength, char displayChar)
{
for (int x=1; x <= lineLength; x=x+1) {
cout << displayChar;
}
cout << endl;
for (int y=y-1; y >= 1; y=y-1) {
cout << displayChar;
}
cout << endl;
} //end drawline
The problem is that cin is a stream (see reference document), so you cannot just stream the value into userChoice as it is an int. Instead you need to use a string:
string response;
cin >> response;
Then you need to parse the string to get the int, using one of the methods in this SO question, like strtol.
Similar question on reading ints here: How to properly read and parse a string of integers from stdin C++
Alternatively, just use the string response for your comparison:
if(response == '1') {
//...
}
for (int y=y-1; y >= 1; y=y-1)
initializes y to an indeterminate value. This means that the loop will have a random, possibly very long, duration.
You can't use cin to set an integer. Because cin is a stream, you can use it to set a string. From there you can convert the string into an integer using atoi. You can look that up on cplusplus.com for more details.
Your implementation should be something like this:
string userChoiceString;
cin >> userChoiceString;
userChoice = atoi(userChoiceString.c_str());

How to count array items within a numeric range

I am tasked with trying to create a histogram from a set of sample values that a user provides. I've created the part of the program that creates the array from sample value input, but now I must take a user input for the histogram. They give min value, max value, and number of bins. So, I'm assuming the number of bins specifies the size of the array for the histogram. But I'm stumped as to how I go to my other array and count how many values are in the specified range for a particular bin. I hope this makes sense. Here is my code for the program thus far:
#include <iostream>
using namespace std;
#define MAX_SAMPLES 100
#define MAX_BINS 20
#define DOUBLE_TOLERANCE 0.0000005
#define EXIT_VALUE -999
int promptUserAndGetChoice(); //function prototype for the menu
//for information describing sample set of data and functions that operated on //those data
class SamplingClass
{
private:
char charID; //the user enters an id for his sample set
int numbOfValues; // the number of good values the user enters
double sampleValues[MAX_SAMPLES]; //for the set of sample values.
//max is 100
public:
bool readFromKeyboard(); //prototype function
bool printToScreen();//protype function
SamplingClass(); //constructor
};
SamplingClass::SamplingClass() //initializing charID
{
charID = 0;
}
bool SamplingClass::readFromKeyboard()
{
int i = 0;
cout << "Enter character identifier for this sample:";
cin >> charID;
cout << "you entered " <<charID << "\n";
cout << "Enter all samples, then enter -999 to end:\n";
while (i < MAX_SAMPLES)
{
cin >> sampleValues[i];
if
(sampleValues[i] < EXIT_VALUE + DOUBLE_TOLERANCE && sampleValues[i] > EXIT_VALUE - DOUBLE_TOLERANCE)
{
break;
}//End if/else
i++;
}//End while
numbOfValues = i;
return true;
}
//this function checks whether charID is empty and then performs accordingly
bool SamplingClass::printToScreen()
{
if (numbOfValues == 0) ///either make a test for existance first or charID
{
cout << "ERROR: Can not print uninitialized sampling!\n";
return false;
}
else
{
cout << "Data stored for sampling with identifier " << charID << ":\n";
cout << "Total samples:" << numbOfValues << "\n";
cout << "Samples (5 samples per line):\n";
int i;
for(i=0; i<numbOfValues;i++)
{
cout << sampleValues[i] << " ";
if (((i+1) % 5) == 0)
{
cout << endl;
}
}
cout << endl;
return true;
}
}
class HistogramClass
{
private:
double minBinValue; //specified by user
double maxBinValue; // specified by user
int numbBins; //specified by user, max of 10
int histoBinCounts[MAX_BINS];
public:
bool setupHistogram(); //prototype function
bool addDataToHistogram(SamplingClass &sampling);//protype function
bool printHistogramCounts();
bool displayHistogram();
};
bool HistogramClass::setupHistogram()
{
cout << "Enter minimum value:";
cin >> minBinValue;
cout << "Enter maximum value:";
cin >> maxBinValue;
cout << "Enter number of bins:";
cin >> numbBins;
cout << "\n";
if (numbBins <= MAX_BINS)
{cin >> numbBins;}
else
cout << "Sorry, the maximum amount of bins allowed is 20. Try again!\n";
}
//function for the menu options that display to user
int promptUserAndGetChoice()
{
cout << "1. Enter a sample set of data values\n";
cout << "2. Print the contents of the current sample set\n";
cout << "3. Reset / Provide values for setting up a histogram\n";
cout << "4. Add the contents of current sample set to histogram\n";
cout << "5. Print bin counts contained in histogram\n";
cout << "6. View the histogram in graphical form\n";
cout << "0: Exit the program\n\n";
}
int main()
{
const int enter_option = 1;
const int printContents_option = 2;
const int reset_option = 3;
const int add_option = 4;
const int printBin_option = 5;
const int viewHist_option = 6;
const int exit_option = 7;
int menuChoice;
SamplingClass sampleSet;
HistogramClass histoSet;
do
{
promptUserAndGetChoice();
cout << "Your Choice: ";
cin >> menuChoice;
if (menuChoice == 1)
{
sampleSet.readFromKeyboard();
cout << "Last Operation Successful: YES\n\n";
}
else if (menuChoice == 2)
{
sampleSet.printToScreen();
}
else if (menuChoice == 3)
{
histoSet.setupHistogram();
}
}
while (menuChoice != 7);
return 0;
}
Each bin in a histograms is typically the same size. So when the user gives you the min, max and number of bins, you can compute the size, and therefore the range, of each bin. Each bin will be of size
bin_size = (max-min)/#_of_bins.
Now to figure out which bin a value goes into, compute
bin = ceil(value/bin_size)
(Or take the floor if you start numbering your bins at 0). And increment the count in this bin. Once you do this for all values, you can print out the count in each bin and this is your histogram.
Update: If min != 0, then the formula is:
bin = (int) (value-min)/bin_size
Using the cast here b/c codemesserupper can't use libs. bin here will be 0-indexed.
If you know the min and max, then any particular value x should be considered to fall into the array at index:
(x - min) / (max - min) * #bins
This will span the range 0..#bins inclusive, so just round down from #bins to #bins-1 when necessary.
EDIT: to be more explicit, and ignoring the object boundaries, the basic approach is to 0 the histoBinCounts then:
for (int i = 0; i < numbOfValues; ++i)
{
double x = sampleValues[i];
int bin = (x - minBinValue) / (maxBinValue - minBinValue) * numbBins;
if (bin >= 0 && bin < numbBins)
++histoBinCounts[bin];
}