I am a bit stuck with my program, The program is to Read in a set of results and then construct a histogram that indicates how many marks are in each decade i.e how many between 10-20 etc.
I have 2 problems
How can I edit my code to only allow the readExamResults to store ones in the range of 0 -100
How can I get the PrintHisto to print the * at a certain setw() dependant on which decade each of the results where in. e.g. If I entered 3,4,5,11,23 It should show 3 * in the <10 decade, 1 in the 10-20 decade and 1 in the 20-30 decade.
any help will be much appreciated.
code:
using namespace std;
void readExamMarks(int examMarks[], int sizeOfArray){
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
for( int idx = 0; idx < sizeOfArray; idx++){
cin >> x;
examMarks[idx] = x;
}
}
void printExamMarks(int examMarks[], int sizeOfArray){
for(int x = 0; x < sizeOfArray; x++){
cout << setw(5) << examMarks[x];
}
cout << endl;
}
void printHisto(int examMarks[], int sizeOfArray){
system("cls");
for( int x = 0; x < 6; x++){
cout << setw(5) << "*" << endl;
}
}
int main()
{
int examMarks[5];
readExamMarks(examMarks, 5);
printHisto(examMarks, 5);
printExamMarks(examMarks,5);
system("PAUSE");
}
How can I edit my code to only allow the readExamResults to store ones
in the range of 0 -100
I guess you meant readExamMarks rather than readExamResults. If so, you would just need to add an if statement to check that the input value is actuall in the range [0..100]. I have also changed your loop statement for to a while because you just want to increase idx when a valid number is entered.
void readExamMarks(int examMarks[], int sizeOfArray)
{
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
int idx = 0;
while(idx < sizeOfarray)
cin >> x;
if((x >=0) && (x <= 100)){
examMarks[idx] = x;
idx++;
}
else
cout << "ERROR: Value must be in range [0...100], please enter a valid value\n";
}
}
Basically you create a new array with an entry for each decade. Then iterate over the exam grades and increase the according decade in the histogram:
vector<int> calculateHistogram(vector<int> grades)
{
vector<int> histogram(10, 0);
for (int i=0; i<grades.size(); i++) {
int decade = grades[i]/10;
histogram[decade] += 1;
}
return histogram;
}
Related
So in this program, I have to do multiplication in a very tedious fashion and for the second loop, the for loop, I'm multiplying one variable by 2 and the output is the product of that multiplication I am wondering how I could go about taking those output values and adding them together. The code and output of the code are below
#include <iostream>
using namespace std;
int main()
{
cout << "Time to do some Martian Math" << endl;
// variables for math
int righthandnum;
int lefthandnum;
cout << "Please enter two numbers" << endl;
// get values to do the martian math
cin >> lefthandnum;
cin >> righthandnum;
//while loop for right hand number
int i = 0;
while (righthandnum >= 1 ) {
//cout << righthandnum << endl;
//if to find out if any values are odd
if (righthandnum % 2 == 0) {
i -= 1;
}
righthandnum = righthandnum / 2;
i++;
}
int num;
for (num = 1; num <= i; num++) {
lefthandnum = lefthandnum * 2;
//lefthandnum + lefthandnum;
cout << lefthandnum << endl;
}
return 0;
}
The output is
Time to do some Martian Math
Please enter two numbers
50
30
100
200
400
800
Thank you so much for any help!
I don't know if this is what you are looking for but maybe a stack or an array might help you
with the array (the easy way), you make a list of N size for the data as an example:
int values[10];
for(int i = 0; i < 10; i++){
std::cin>>values[i];
}
for(int i = 0; i < 10; i++){
std::cout<<"List element "<<i<<": "<<values[i]<<std::endl;
}
while the stack as I've used it it's a bit more complex and requires pointers.
this is a video (sorry it's in Spanish): https://youtu.be/joAw2jWgZqA
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 this is for a lab assignment and I already have it working, but one thing is bothering me. The assignment involves creating a 1-dimensional array and then manipulating it. I am supposed to allow a max of 100 inputs but the user does not have to use all 100. Right now, I am using a while statement to either break or allow another input to be entered. To break the statement, you have to enter a negative number (this is what I don't like and want to change). What other options are there to end the user input, once they are done entering their numbers? Is it possible to end the loop once you hit enter with nothing typed?
I have searched stackoverflow for the last 3 days and found some compelling stuff but could never get it to work.
Note, I get the void function is redundant here but that's besides the point (unless it actually affects my ability to achieve what I want).
Also, thanks in advance.
here is my code so far (my while statement is in the main)... be kind I'm a newbie to coding.
#include <iostream>
using namespace std;
void reverseElements(int array[], int size)
{
int tmp;
int j;
int i = size;
j = i - 1;
i = 0;
while (i < j)
{
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
cout << "I will now reverse the elements of the array." << endl;
cout << endl;
for (i = 0; i < size; i++)
{
cout << array[i] << " " << endl;
}
}
int main()
{
const int NUM_ELEMENTS = 100;
int iArr[NUM_ELEMENTS];
int i;
int myInput;
cout << "Enter your numbers, then enter a negative number to finish" << endl;
cout << endl;
for (i = 0; i < NUM_ELEMENTS; i++) //loop to obtain input
{
cin >> myInput;
if (myInput < 0) //checks for negative number to end loop
{
break;
}
else //continues to allow input
{
iArr[i] = myInput;
}
}
cout << endl;
reverseElements(iArr, i);
return 0;
}
Probably the easiest solution: let your user choose how many numbers to write before actually writing them.
int readNumbersCount()
{
int const numbersMin = 1;
int const numbersMax = 100;
int numbersCount = -1;
while (numbersCount < numbersMin || numbersCount > numbersMax)
{
std::cout <<
"How many numbers are you going to enter? Choose from " <<
numbersMin << " to " << numbersMax << ":\n";
std::cin >> numbersCount;
}
return numbersCount;
}
int main()
{
int const numbersCount = readNumbersCount();
for (int i = 0; i < numbersCount; ++i)
{
// read the numbers etc.
}
return 0;
}
I wrote readNumbersCount() as a separate function to extract numbersMin and other "one-use" identifiers from main() and to make main()'s numbersCount const.
I have edited the main function a little bit.
Here the user is asked how many elements he wants to enter .
and doing the memory allocation dynamically so as to save space
int main()
{ int n=101;
while(n>100){
cout<<"How many numbers do you want to enter";
cin>>n;
}
int *ptr=new(nothrow)int[n];
for (int i=0;i<n;i++){
cout << "Enter your number" << endl;
cin>>ptr[i];
}
cout << endl;
reverseElements(ptr, n);
return 0;
}
So I have succeeded in confusing the hell out of myself in doing this. I am trying to get it to calculate the average of the weights entered into the array minus the lowest weight in the array. I'm using functions and somewhere along the line I confused myself with passing variables. It would be much appreciated if someone could give me a pointer and tell me if I'm way off base or not. Also how would I compare the values entered to a validation code? I have a line commented out that I was fiddling with, but never got working.
#include <iostream>
using namespace std;
int getWeight();
int findLowest(int arrayWeight);
double calcAverage(int weight);
bool askToContinue();
int main(){
do{
int weights = getWeight();
double lowest = findLowest(weights);
double average = calcAverage(weights);
}
while(askToContinue());
}
int getWeight() {
//Variables
int weights[5]; //array
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
cin >> weights[counter];
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
return -1;
/*
do
{
//Gather user input of amount of discs
cout << "How many discs do you wish to purchase?" << endl;
cout << "Please enter a number between 1 and 1,000,000" << endl;
cin >> weights;
cout << endl;
validAmount = (weights > 5) && (weights <= 500); // Tests if the amount entered is valid
if (!validAmount) // Prompts user amount entered was invalid
{
cout << "Invalid Amount. Please try again!" << endl;
}
}
while(!validAmount); // Runs loop again if the amount entered was not valid
return discs;
*/
}
int findLowest(int arrayWeight){
int lowWeight = 999999;
if(lowWeight > arrayWeight)
{
lowWeight = arrayWeight;
}
cout << arrayWeight;
system("PAUSE");
return arrayWeight;
}
double calcAverage(int weight){
//Variables
float avgWeight = 0;
int sumWeight = 0;
//Calls findLowest function to find lowest value
int lowestWeight = findLowest(weight);
//Calculates the average score
return weight;
}
bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits.
{
char userResponse = ' ';
bool validInput = false;
do
{
cout << endl;
cout << "Do you wish to continue?" << endl;
cout << "Enter y for 'yes' or n for 'no'" << endl;
cin >> userResponse;
validInput = (userResponse == 'y') || (userResponse == 'n');
if (!validInput)
{
cout << "Invalid response. Please try again!" << endl;
}
} while (!validInput);
return(userResponse == 'y');
}
You have a number of issues, the first being you need to understand the data types you're working with. You should declare the array once and then pass around a pointer to that array. These are a better set of declarations and for convenience set up a constant for the number of weights.
#include <iostream>
using namespace std;
const int numWeights = 5;
void getWeights(int weights[]);
int findLowest(int weights[]);
double calcAverage(int weights[]);
bool askToContinue();
int main() {
do {
int weights[numWeights];
getWeights(weights);
double average = calcAverage(weights);
cout << "Average: " << average << endl;
}
while (askToContinue());
}
getWeights was mostly ok, but use the passed in array.
void getWeights(int weights[]) {
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
int weight;
cin >> weight;
while (weight < 5 || weight > 500)
{
cout << "Invalid weight, should be between 5 and 500" << endl;
cin >> weight;
}
weights[counter] = weight;
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
}
For findLowest you need to keep track of the lowest value and the lowest index. By remembering the index of the lowest value, you will make the average easier. Your 99999 magic number isn't needed since we know there will always be a lowest value in your set. Start with index 0 and the first value. If you find something smaller, update the value and index. When the loop ends you'll have the first index of the lowest value. Note that the loops starts at 1 (the second item).
int findLowest(int weights[]) {
int lowestVal = weights[0];
int lowestIndex = 0;
for (int i=1; i<numWeights; i++) {
if (weights[i] < lowestVal) {
lowestVal = weights[i];
lowestIndex = i;
}
}
return lowestIndex;
}
For the average find the lowest index, add up all the weights but skip the index of the lowest, convert to double so you can get a good average and return the value.
double calcAverage(int weights[]) {
int lowestIndex = findLowest(weights);
int total = 0;
for (int i=0; i<numWeights; i++) {
if (i != lowestIndex) {
total += weights[i];
}
}
return (double)total/(double)(numWeights-1);
}
My average function is dropping the last element.
I tested it using the numbers 0, 5, 10, 20 in which I get an average of 5.00 instead of 8.75.
If you switch the numbers around, the last element still gets dropped.
Also, there's another problem that happened when my teacher tried to run it, but one I've been unable to replicate which is some weird large number getting thrown in the first element after being sorted.
#include <iostream>
#include <cstdlib>
#include <string>
#include <iomanip>
using namespace std;
int getNumber();
void getMovieData(int *, int);
void sort(int *, int);
double getAverage(int *, int);
void print(int *, int);
int main()
{
int students, i, j;
int *movies;
cout << "Enter the number of Students surveyed: ";
i = getNumber();
movies = new int[i];
getMovieData(movies, i);
cout << endl << "--- Here is the data you entered ---" << endl;
print(movies, i);
cout << endl << "--- Here is the data after being sorted --" << endl;
sort(movies, i);
double average = getAverage(movies, i);
print(movies, i);
cout << endl << "The average number of movies seen is " << fixed
<< showpoint << setprecision(2) << average << endl; //rounding to
system("PAUSE");
return 0;
}
// Function used to input positive number
int getNumber()
{
int number;
cin >> number;
// Validation
while (number < 0)
{
cout << endl << "Number cannot be negative: "
"Please enter a nonnegative value: ";
cin >> number;
}
return (number);
}
// Function to input values into the array, movies of size SIZE
void getMovieData(int *ptrToArray, int SIZE)
{
for (int i = 0; i < SIZE; i++)
{
cout << endl << "Enter the number of movies Student " << i+1 << " saw: ";
ptrToArray[i]= getNumber();
}
}
// Bubble Sort the Data
void sort( int *ptrToArray, int SIZE)
{
for (int j = 0; j < SIZE; j++)
{
for (int i = 0; i < SIZE; i++)
{
if (ptrToArray[i] < ptrToArray[i+1])
{
int temp = ptrToArray[i];
ptrToArray[i] = ptrToArray[i+1];
ptrToArray[i+1] = temp;
}
}
}
}
// Simple Average function; returns average to average in main
double getAverage(int *ptrToArray, int SIZE)
{
double total=0;
for(int i=0; i < (SIZE); i++)
{
total += ptrToArray[i];
}
double average = total/(SIZE -1);
return (average);
}
//A function to print the arrays only! the average is printed in main
void print(int *ptrToArray, int SIZE)
{
for (int i = 0; i < SIZE; i++)
{
cout << ptrToArray[i] << setw(10);
}
}
The numbers to input are this:
4
0
5
10
20
with an output of 20, 10, 5, 0 and average of 5.00
and the second set of numbers is:
4
4
22
3
55
with an output of 225982769 55 22 4 (sorted) and average of 32283264.29
With the second set of numbers, I was unable to replicate the output she got as I got the correct sort, but obviously the wrong average. Any help you can give me is much appreciated.
EDIT: There was an issue with the compiler not including the file I was working with in the Project and instead, using the old one. The only difference was
total/7
versus
total/SIZE
which is why the average was off. It SEEMED like it was dropping the last element but it really just so happened to be a coincidence that they totaled 35 and divided by 7 is 5.00 which is also the average if you dropped the 20.
Once I changed the right .cpp file, it worked perfectly (pretty much all the changes you guys suggested had been the original code, and were changes I made to try and alter the average, which didn't change because I wasn't altering the right source file. In short, problem solved.)
You need to include the last element in you averaging function. Either do
for(int i = 0; i < SIZE; ++i)
or
for(int i = 0; i <= (SIZE - 1); ++i)
You have an off-by-one error
for(int i=0; i < (SIZE - 1); i++)
You need i < SIZE. Same goes for the division,
double average = total/(SIZE -1);
Here you need SIZE, not SIZE-1 too.
Also,
system("PAUSE");
Should be avoided. It's better to use something like getchar().