I am trying it this way. seems to be more simplified. just trying to figure out now how to include the month names and to get the program to output the name of the rainiest month not the number the user inputs.
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int a[12];
int x;
for (x=0; x<12; x++)
{
cout << "Insert days of rainfall for month "<<x+1<<endl;
cin >>a[x];
}
int max;
int min;
max = a[0];
min = a[0];
int e=0;
while (e<12)
{
if (a[e]>max)
{
max = a[e];
}
else if (a[e]<min)
{
min = a[e];
}
e++;
cout<<"The rainiest month was " <<max<<endl;
cout<<"The least rainy month was " <<min<<endl;
getch ();
return 0;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Your average calculation is off a little, you have to take into consideration the order of operations when it comes to math. Multiplication and division are always done first, then addition and subtraction. What you end up with is that ONLY dec is divided by 12, and THEN you add all the other days to it. To fix this, you need to wrap the additions of all of the months in parentheses to force the addition to happen first, then do the divide after. In this case, you can just use your year variable since it is already all of the months added together and divide it by 12.
As far as your question goes, you want to show the highest and lowest values input, but I don't see any attempt to solve this in your code. I feel less inclined to just write the code for you so I will just give a brief explanation of what you need to do instead. Look at the value for each month, each time you look at the next month, you compare it with the current highest and current lowest values you remember. When the new month has a new higher, or new lower, value you replace the value you remember. Once you cycle through every month you will end up with your highest and lowest values.
The fastest and the most clean way is to use a container such as an std::vector. Then sort it using std::sort.
// Our container
std::vector<double> userInput;
// Populate the vector. Please don't cin into a double!
// Sort it.
std::sort (userInput.begin(), userInput.end());
// The highest value will be the last value in the vector
// whilst the lowest value will be the first one
Related
I've got a bit of a conundrum. I'm currently trying to create a user-defined function to sort a column (in ascending order) of a 2D int array I created and populated in the main function. I feel like I'm close, but for some reason the final output is incorrect, it provides a number for the final value that isn't even in the array. Judging from the value provided and the extra few seconds it takes to compile, I'm assuming I've messed up my bounds/ gone beyond them at some point within the code, but I've been fighting this thing for hours to no avail and I feel fresh (and likely more experienced) eyes would be-be of some use. I'm still in my "Intro to" class for programming, so ripping me a new one for obvious errors is encouraged as my final is this Thursday and any and all pointers/tips are appreciated. Cheers!
#include <iostream>
using namespace std;
void sort2D(int arr[3][5], int rows, int columns) //the problem child
{
int userCol;
cout<<"Please enter the number of the column you'd like to sort: "<<endl;
cin>>userCol; //ask for appropriate column
for (int row_index=0; row_index<rows; row_index++) //start with first row and continue for all values in code
{
int temp;
if ((arr[row_index][userCol-1]<arr[row_index+1][userCol-1]))//if first value of selected column is less than next value
{
temp = arr[row_index+1][userCol-1];//create copy of second value
arr[row_index+1][userCol-1]=arr[row_index][userCol-1]; //replace second value with first value
arr[row_index][userCol-1]=temp;//set first equal to second's original value
}
}
for(int i=0; i<rows; i++)//print that shiz
{
for(int j=0; j<columns; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
int main()
{
const int rows = 3;
const int columns = 5;
int arr[rows][columns];
for (int row_index=0; row_index<rows; row_index++)
{
for (int column_index=0; column_index<columns; column_index++)
{
arr[row_index][column_index] = (50+rand()%51);
cout << arr[row_index][column_index]<<" ";
}
cout << endl;
}
findMaxandIndex(arr, rows, columns);//i left my code for this out because it's working and isn't utilized in the problem code
cout << endl;
sort2D(arr, rows, columns);
return 0;
Your sort function is very close to bubble sort, one of the simplest sorting algorithms to understand and implement. With a little modification, your code will work :
void sort2D(int arr[3][5], int rows, int columns) //the problem child
{
//input userCol ...
//sorting start here ...
bool found = true; //we can quit the loop if the array is already sorted.
for (int bubble = 0; bubble < rows-1 && found ; bubble++)
{
found = false;
for (int row_index=0; row_index < rows - bubble - 1; row_index++)
{
int temp;
if ((arr[row_index][userCol-1] < arr[row_index+1][userCol-1]))//if first value of selected column is less than next value
{
//swap two elements.
temp = arr[row_index+1][userCol-1];//create copy of second value
arr[row_index+1][userCol-1]=arr[row_index][userCol-1]; //replace second value with first value
arr[row_index][userCol-1]=temp;//set first equal to second's original value
found = true; //we found something, continue to sort.
}
}
}
//print out the result ...
}
As you start in C++, an advice is to use C++ facilities if possible : std::vector for your array and std::qsort for sorting elements.
Issue 1: The int arr[3][5]; you declared in sort2D() is NOT the same as the int arr[rows][columns]; you declared in main().
lesson : check (or web search) on "pass by reference" & "pass by value" . For simplicity, I recommend pass by value.
Issue 2: The sort only compare 2 values and only run for 1 pass.. so {2,1,4,3} may get sorted to {1,2,3,4} but {1,4,3,2} will only get to {1,3,2,4} with 1 pass. #ZDF comment is helpful for this part.
Issue 3: at this line.. temp = arr[row_index+1][userCol-1]; when row_index is 2, this will refer to a location that is not in the arr[][] array. arr are only defined for row = 0,1,2 .. not 3 (when row_index is 2, row_index+1 is 3). This may answer :
it provides a number for the final value that isn't even in the array.
Solution.. hurm. I suggest you have a look and try.. and share where you stuck at. you may also test the sort2D in the main function before doing it as separate function. IMHO, you can start by 1st looking for the sorting algorithm that works (with sample data).. Then work on making it work in this project. ( :
p/s: I don't see my post as an answer.. more like a correction guide.
Im trying to write a console application in c++ that will let the user input a series of numbers and the program should get the sum of all numbers, the average number, the largest and the second largest number.
For example:
Enter a couple of numbers : 10 12 -5 20 -2 15 0
Sum = 50
Average value = 8.3
Largest number = 20
Second largest = 15
#include<iostream>
#include<conio.h>
using namespace std;
int main( )
{
int a[5];
cout << "We are going to find the max value"<< endl;
int x;
for (x=0; x<5; x++)
{
cout<<"insert values"<<x+1<<endl;
cin>>a[x];
}
int max;
int min;
max = a[0];
min = a[0];
int e=0;
while (e<5)
{
if (a[e]>max)
{
max = a[e];
}
e++;
}
cout<<"Max value in the array is.."<<max<<endl;
getch();
return 0;
}
This is my progress so far.
Although, I have some concerns.
How do I let the user input the numbers like in the example and store them in a array with unknown size?
I'll try to figure out a way to count the avg, sum and second largest while waiting for this answer :)
Thanks!
To input an unknown number of elements, you use std::vector, inputting
until the user tells you to stop, typically by inputting an end of file:
std::vector<int> values;
int i;
while ( std::cin >> i ) {
values.push_back( i ) ;
}
If you're looking for some other type a signal for the end, you'll
probably have to read line by line, checking whether the line contains
your end criteron, and then use std::istringstream to parse the
integer.
For the rest: it may not correspond to the goal of the exercise, but
the standard library has a couple of functions which could make things
significantly simpler: std::max_element, for example, or
std::accumulate. And <conio.h> is not very portable, and is
deprecated on the systems which do support it.
If you can't use std::vector, you might want to learn about dynamic memory allocation.
int *a = new int[size];
this is my first time posting here. I'm working on a lab for my CS II class (it's already past due, so I won't get any points for it at this point, but I'd still really like to understand what I'm doing wrong so that I can improve. The code is nowhere near complete, but I've hit a hangup that's keeping me from proceeding. Apologies in advance, I'm very rusty at this, and before I was rusty, I was very new. Also, I was up 'til about 4 in the morning trying to get this to work last night, so my code is probably pretty gnarly-looking at the moment.
Okay, so my issue is this: while single-stepping the code, the first function, getNoMonths, runs perfectly fine. It prompts the user for the number of months of sales they'd like to process the data for, and stores the number in no_Months back in main. The validation for the value needing to be between 3 and 6 also works fine.
When we get to getSales, the problem arises. The function prompts for the sales values of however many months the user defined earlier. It seems like it works perfectly. Upon closer inspection, however, it seems that only the first value is actually being stored in sales, which is supposed to be an array, the size of which is dynamically allocated according to how many months the user defined during getNoMonths.
I'm sure that whatever I'm doing wrong is incredibly simple, I can feel it. I've been flipping through the text again, trying to learn as much as I can about how arrays and dynamic memory allocation and pointers all work. I get the ideas behind them, but as you can probably see, I'm really struggling with the actual implementation.
I know that what I NEED to do here is:
set up an array to hold sales data for each month
have the size of that array match the number of months as input by the user
...I'm just not sure how to actually do it. I also know I need to have a pointer in order for the second bullet item to happen, but again, I'm not really clear on what exactly I need to do.
TL;DR I need some help getting this sales array to hold ALL the values input by the user, not just the first one. To do this, I'll probably need help with setting up a pointer to dynamically allocate the size of the sales array, and preferably an explanation on how the hell all this actually helps me and isn't just confusing and redundant, lol.
Source code follows:
//Jesse Holland
//Lab1Out
//Processes Sales Data, Displays as a Bar Graph presentation
#include <iostream>
#include "graph1.h"
using namespace std;
//FUNCTION PROTOTYPES
int getNoMonths(int& no_months); //prompts for number of months of sales data to be processed
void getSales(int* sales, int no_months); //prompts for sales data, stores corresponding data in "sales"
int getMax(int* sales, int no_months, double & max); //maximum value for "sales" array
int getMin(int* sales, int no_months, double & min); //minimum value for "sales" array
double getAvg(int* sales, int no_months, double & avg); //computes avg of sales data stored in "sales" array
void displayResults(int* sales, int no_months, int max, int min, double avg); //displays bar chart diagram
//MAIN FUNCTION START
int main()
{
double max = 0;
double min = 0;
double avg = 0;
int no_months = 0;
//prompt for number of months
getNoMonths(no_months);
//variable declaration
int * sales = new int[no_months];
//prompt for sales data
getSales(sales, no_months);
//maximum value of "sales" array
getMax(sales, no_months, max);
//minimum value for "sales" array
getMin(sales, no_months, min);
//computes avg of sales data stored in "sales" array
getAvg(sales, no_months, avg);
//displays bar chart diagram in graphics window
displayResults(sales, no_months, max, min, avg);
return 0;
}
//FUNCTIONS IMPLEMENTATION START
int getNoMonths(int& no_months) // int* months)
{
do
{
cout << "Please enter the number of months you'd like to process: <must be at least 3, but no more than 6>:";
cin >> no_months;
//int* months = new int[no_months];
}while ((no_months < 3) || (no_months > 6));
return no_months;
}
void getSales(int* sales, int no_months)
{
int count = 0;
for (count = 0; count < no_months; count++)
{
cout << "Please enter sales for month #" << (count + 1) << ": ";
cin >> sales[count];
}
}
int getMax(int* sales, int no_months, double & max)
{
//int max = 0;
for(int count = 0; count < no_months, count++;)
{
if (sales[count] > max)
max = sales[count];
}
return max;
}
int getMin(int* sales, int no_months, double & min)
{
//int min = 0;
int count = 0;
for (count = 0; count < no_months; count++)
{
if (sales[count] < min)
min = sales[count];
}
return min;
}
double getAvg(int* sales, int no_months, double & avg)
{
int sum = 0;
for(int count = 0; count < no_months; count++)
sum += sales[count];
return avg = (sum/no_months);
}
void displayResults(int* sales, int no_months, int max, int min, double avg)
{
cout << "The maximum is " << max << ". \n";
cout << "The minimum is " << min << ". \n";
cout << "The average is " << avg << ". \n";
}
Thanks very, very much in advance for any and all help. I'm very, very green at all this, and although I'm trying very hard to get it, it seems impossible. I'm determined to learn how all this works and to be able to UNDERSTAND it so I can replicate it myself, but right now I need a little help getting there. It's hard not having any friends that no anything about this stuff and a professor who isn't terribly interested in sitting down with me and helping me work it out, either. Anyway, I look forward to hearing from you guys and hopefully learning some stuff. Maybe one day I can learn enough to be able to return the favor to newer people than I.
UPDATE: Updated source code; average is being properly calculated and output now, but still can't get max and min to do the same. Thanks for the help thus far, any further input will of course be appreciated.
Your main problem seems to be
int no_months = 0; followed by int * sales = new int [no_months]; which basically allocates an array of size 0. Try calling getNoMonths before allocating the array and fix return types.
I'm pretty new to C++, and I need help figuring out the code for dropping the lowest value of a randomly generated set of numbers. Here is my code so far:
//Create array and populate the array with scores between 55 and 10
// Drop lowest Score
#include <iostream>
#include <cstdlib>//for generating a random number
#include <ctime>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
//function prototype
int *random (int);
int main()
{ int *numbers; //point to numbers
//get an array of 20 values
numbers = random(20);
//display numbers
for (int count = 0; count < 20; count++)
cout << numbers[count] << endl;
cout << endl;
system("pause");
return 0;
}
//random function, generates random numbers between 55 and 100 ??
int *random(int num)
{ int *arr; //array to hold numbers
//return null if zero or negative
if (num <= 0)
return NULL;
//allocate array
arr = new int[num];
//seed random number generator
srand(time (0));
//populate array
for (int count = 0; count < num; count++)
arr[count] = (rand()%(45) +55);
//return pointer
//
return arr;
}
For this piece of code, how would I sort or find the lowest score to drop it after the function returns the random numbers?
int main()
{ int *numbers; //point to numbers
//get an array of 20 values
numbers = random(20);
//display numbers
for (int count = 0; count < 20; count++)
cout << numbers[count] << endl;
cout << endl;
system("pause");
return 0;
}
Your suggestions are appreciated!
In general, to find the lowest value in an array, you can follow this psuedo-algorithm:
min = array[0] // first element in array
for (all_values_in_array)
{
if (current_element < min)
min = current_element
}
However, you can't "drop" a value out of a static array. You could look into using a dynamic container (eg. vector), or swapping the lowest value with the last value, and pretending the size of the array is 1 less. Another low level option would be to create your own dynamic array on the heap, however, this is probably more complicated than you are looking for.
Using an vector would be much easier. To drop the lowest element, you just have to sort in reverse order, then remove the last element. Personally, I would recommend using a vector.
The obvious approach to find the smallest element is to use std::min_element(). You probably want to use std::vector<T> to hold your elements but this isn't absolutely necessary. You can remove the smallest value from an array like this:
if (count) {
int* it = std::min_element(array, array + count);
std::copy(it + 1, array + count--, it);
}
Assuming you, reasonable used std::vector<int> instead, the code would look something like this:
if (!array.empty()) {
array.erase(std::min_element(array.begin(), array.end()));
}
First find the index of the lowest number:
int lowest_index=0, i;
for (i=0; i<20; i++)
if (arr[i]<arr[lowest_index])
lowest_index=i;
Now that we know the index, move the numbers coming after that index to overwrite the index we found. The number of numbers to move will be 19 minus the found index. Ie, if index 2 (the third number, since the first is at index 0) is lowest, then 17 numbers comes after that index, so that's how many we need to move.
memcpy(&arr[lowest_index],&arr[lowest_index+1],sizeof(int)*(19-lowest_index))
Good luck!
Sort the array ascending.
The lowest value will be at the beginning of the array.
Or sort the array descending and remove the last element.
Further to what others have said, you may also choose to use something like, perhaps a std::list. It's got sorting built-in, also offering the ability to define your own compare function for two elements. (Though for ints, this is not necessary)
First, I typically typedef the vector or list with the type of the elements it will contain. Next, for lists I typedef an iterator - though both of these are merely a convenience, neither is necessary.
Once you've got a list that will holds ints, just add them to it. Habit and no need to do otherwise means I'll use .push_back to add each new element. Once done, I'll sort the list, grab the element with the lowest value (also the lowest 'index' - the first item), then finally, I'll remove that item.
Some code to muse over:
#include <cstdio>
#include <cstdlib>
#include <list>
using namespace std;
typedef list<int> listInt;
typedef listInt::iterator listIntIter;
bool sortAsc(int first, int second)
{
return first < second;
}
bool sortDesc(int first, int second)
{
return first > second;
}
int main (void)
{
listInt mList;
listIntIter mIter;
int i, curVal, lowestScore;
for (i=1; i<=20; i++)
{
curVal = rand()%45 + 55;
mList.push_back(curVal);
printf("%2d. %d\n", i, curVal);
}
printf("\n");
mList.sort();
// mList.sort(sortAsc); // in this example, this has the same effect as the above line.
// mList.sort(sortDesc);
i = 0;
for (mIter=mList.begin(); mIter!=mList.end(); mIter++)
printf("%2d. %d\n", ++i, *mIter);
printf("\n");
lowestScore = mList.front();
mList.pop_front();
printf("Lowest score: %d\n", lowestScore);
return 0;
}
Oh, and the choice to use printf rather than cout was deliberate too. For a couple of reasons.
Personal preference - I find it easier to type printf("%d\n", someVar);
than cout << someVar << endl;
Size - built with gcc under windows, the release-mode exe of this example is 21kb.
Using cout, it leaps to 459kb - for the same functionality! A 20x size increase for no gain? No thanks!!
Here's an std::list reference: http://www.cplusplus.com/reference/stl/list/
In my opinion the most optimal solution to your problem would be to use a linked list to store the numbers, this way you can use an algorithm with complexity O(N) = N to find the smallest element in the list, it is a similar finding method given by user1599559 or Mikael Lindqvist, you only need stored together with the minimum value the pointer to the Item(ItemX) in the linked list that store it, then to eliminate Item X just tell Item X - 1 points to Item X + 1 and free memory allocated by Item X
I tried to do this:
(n-input number 1<=n<=100, firstly x=0.1)
I have to print a table with a count of summations and X-es
I tried to solve that with recursion, but it's takes very long time:(
I only want to know the algorithm.
My attempt:
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
double x = 0.1, mx2 = -x*x*2;
int i;
double part = 1, sum = 1;
for (i = 2; i < N; i+=2) {
part *= mx2/((i-1)*i);
sum += part;
cout<<"sum= "<<sum<<endl;
}
return 0;
}
Is that right?
For calculating x^2n note that in previous step you have x^2(n-1) so just required to multiply it with x^2.
Also for calculating (2n)!, in previous step you had (2(n-1))! so just need to multiply it by (2n-1)*2n.
In fact just one extra variable helps you, which holds the value of x^2n / (2n)! in each step, to just multiply it to appropriated value in next step.
Edit:
Your current code problem is in this line:
cout<<"sum= "<<sum<<endl;
cause cout is very time consuming job, and in each iteration of for loop you want do it.
Instead of that, if is required to have such a cout, create char stream and insert the value of your sum into this, and at last just with one cout show all results.