So basically I am trying to write a program which accepts an array of integers and then outputs the Max Min and smallest Mode and how many times it occurs.
I have been able to find both max and min and mode, but instead of the smallest mode my code outputs the one that occurs first. And i am not sure how to handle an input with more than one mode.
Below i’ll post my code:
#include
using namespace std;
int main() {
int p,max,min,mode;
cout << "Enter the number of postive integers:"<< endl;
cin >> p;
int pos[p];
cout << "Now enter postive integers!" <<endl;
for(int i=0; i<p; i++) {
cout << "Positive integer " << i+1 << ":";
cin >> pos[i]; }
max =pos[0];
min =pos[0];
for( int i=0; i<p; i++){
if(pos[i]> max) max=pos[i];
if(pos[i]< min) min=pos[i];
}
cout << "Max=" << max << endl;
cout << "Min=" << min << mode= pos[0];
int count[20];
int t=0;
for(int c=0;c<p; c++)
{
for(int d=0;d<p;d++)
{
if(pos[c]==pos[d])
{
count[c]++;
t++;
}
}
int modepos, maxno=count[0];
for(int e=1;e<p;e++)
{
if(maxno<count[e])
{
maxno=count[e];
modepos=e;
}
}
mode=pos[modepos];
if(t==1) {
cout << "There is no positive integer occuring more
than once." << endl;
}
else {
cout <<"The most occuring positive integer is:"<< mode;
cout << "\nIt occurs " << t << " times." << endl;
} return 0; }
there may be simpler and better ways to code this but since i’m a beginner and have only learned loops/conditionals/arrays/variable declaration etc I can only use them in the program, any help will be appreciated.
Do you learn about std::map? The algorithm for counting how many times of an element on an array is very simple with std::map
std::map<long, long > mapFreq;// first: for store value of array pos, second for store value's counter
mapFreq.insert(std::pair<long, long>(pos[0], 1));
for(int i = 1; i < dsize; i++)
{
auto &it = mapFreq.find(pos[i]);
if(it != mapFreq.end())
{
it->second++;
}
else
{
mapFreq.insert(std::pair<long, long>(pos[i], 1));
}
}
Then you can loop through map Freq for what you need:
int number, counter;
for(auto it : mapFreq)
{
if(it.second < counter)
{
number = it.first;
counter = it.second;
}
}
Maybe you can try doing this:
#include <iostream>
#include <algorithm> //for sorting
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++) cin>>a[n];
sort(a,a+n);
int b[a[n-1]];
for(int i=0;i<a[n-1];i++) b[i]=0;
for(int i=0;i<n;i++) b[a[i]]++;
cout<<"Largest number = "<<a[n-1]<<endl;
cout<<"Smallest number = "<<a[0]<<endl;
int rep=0;//repetition
int mode=0;
for (int i=0;i<a[n-1];i++){
if(b[i]>rep){
rep=b[i];// set times of repetition
mode=i;// set new mode
}
}
cout<<"Mode = "<<mode<<endl;
}
Related
I finished this code homework assignment tonight. I thought I was done, but I just realized that my "Average" value is coming out wrong with certain values. For example: When my professor entered the values 22, 66, 45.1, and 88 he got an "Average" of 55.27. However, when I enter those values in my program, I get an "Average" of 55.25. I have no idea what I am doing wrong. I was pretty confident in my program until I noticed that flaw. My program is due at midnight, so I am clueless on how to fix it. Any tips will be greatly appreciated!
Code Prompt: "Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings. Use pointer notation rather than array notation whenever possible."
Professor Notes: The book only states, "Input Validation: Do not accept negative numbers for test scores." We also need to have input validation for the number of scores. If it is negative, including 0, the program halts, we should consider this situation for 'counter' not to be negative while we have a loop to enter numbers. So negative numbers should be rejected for the number of scores and the values of scores.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
if (numberOfScores < 0) {
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter);
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter);
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0");
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue;
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
I try to start my answers with a brief code review:
#include <iostream>
#include <iomanip>
using namespace std; // Bad practice; avoid
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
// This is not input validation, I can enter two consecutive bad values,
// and the second one will be accepted.
if (numberOfScores < 0) {
// Weird formatting, this blank line
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
// The homework, as presented, doesn't say you have to treat 0 differently.
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
// Declare your loop counter in the loop
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter); // Why not use numberOfScores?
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter); // Same as above.
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0"); // Meh, I suppose if you're on VS
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue; // Unnecessary, and also the culprit
// This looks like selection sort
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
When you are sorting your array, you keep track of the minValue as an int and not a double. That's why your average of the sample input is incorrect. 45.1 is truncated to 45 for your calculations. You don't need to keep track of the minValue at all. Knowing where the minimum is, and where it needs to go is sufficient.
But as I pointed out, there are some other serious problems with your code, namely, your [lack of] input validation. Currently, if I enter two consecutive bad numbers, the second one will be accepted no matter what. You need a loop that will not exit until a good value is entered. It appears that you are allowed to assume that it's always a number at least, and not frisbee or any other non-numeric value.
Below is an example of what your program could look like if your professor decides to teach you C++. It requires that you compile to the C++17 standard. I don't know what compiler you're using, but it appears to be Visual Studio Community. I'm not very familiar with that IDE, but I imagine it's easy enough to set in the project settings.
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
// Assumes a number is always entered
double positive_value_prompt(const std::string& prompt) {
double num;
std::cout << prompt;
do {
std::cin >> num;
if (num <= 0) {
std::cerr << "Value must be positive.\n";
}
} while (num <= 0);
return num;
}
int main() {
// Declare variables when you need them.
double numberOfScores =
positive_value_prompt("How many test scores will you enter? ");
std::vector<double> scores;
for (int counter = 0; counter < numberOfScores; counter++) {
scores.push_back(positive_value_prompt("Enter test score: "));
}
std::sort(scores.begin(), scores.end());
for (const auto& i : scores) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "\nAverage Score: "
<< std::reduce(
scores.begin(), scores.end(), 0.0,
[size = scores.size()](auto mean, const auto& val) mutable {
return mean += val / size;
})
<< '\n';
}
And here's an example of selection sort where you don't have to worry about the minimum value. It requires that you compile to C++20. You can see the code running here.
#include <iostream>
#include <random>
#include <vector>
void selection_sort(std::vector<int>& vec) {
for (int i = 0; i < std::ssize(vec); ++i) {
int minIdx = i;
for (int j = i + 1; j < std::ssize(vec); ++j) {
if (vec[j] < vec[minIdx]) {
minIdx = j;
}
}
int tmp = vec[i];
vec[i] = vec[minIdx];
vec[minIdx] = tmp;
}
}
void print(const std::vector<int>& v) {
for (const auto& i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
std::mt19937 prng(std::random_device{}());
std::uniform_int_distribution<int> dist(1, 1000);
std::vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(dist(prng));
}
print(v);
selection_sort(v);
print(v);
}
I opted not to give your code the 'light touch' treatment because than I would have done your homework for you, and that's just not something I do. However, the logic shown should still be able to guide you toward a working solution.
Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;
cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter? ";
cin >> size[ARRAY_SIZE];
cout << "Enter your number: \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> size[i];
}
cout << "\nYour numbers reversed are:\n";
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Your infinite loop is because i is unsigned, so i >= 0 is always true.
Here's a C++-ified version:
#include <iostream>
#include <vector>
int main() {
std::cout << "You may enter up to 50 integers:\n";
std::cout << "\nHow many would you like to enter? ";
int count;
std::cin >> count;
// Use a std::vector which can be extended easily
std::vector<int> numbers;
for (int i = 0; i < count; ++i) {
std::cout << "Enter your number: \n";
int v;
std::cin >> v;
// Add this number to the list
numbers.push_back(v);
}
std::cout << "\nYour numbers reversed are:\n";
// Use a reverse iterator to iterate through the list backwards
for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
// An iterator needs to be de-referenced with * to yield the value
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
std::cout << numbers[i];
}
Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.
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;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi i'm trying to Write a program in C++ to, generate and print 20 random numbers, between 0 to 999, and do the following operations without using inbuilt functions, find and print the: min value, max value, average, median, standard deviation, variance. Do a binary search on the 15th element. Please help me with the code.
So far i've done this much
#include
#include
#include
using namespace std;
void minimum(int[], int);
void maximum (int[], int);
void average(int[], int);
void median(int[], int);
void mean(int[], int);
void sort(int[], int);
int ra()
{
int r = rand() % 1000;
return r;
}
int main ()
{
srand(time(NULL));
ra();
int array[20];
int num=20;
for (unsigned int i = 0; i < num; i++)
{
array[i] = ra();
cout << "Index: " << i << ", random number: " << array[i] << endl;
}
minimum();
new_array[20];
num=20;
for (unsigned int i = 0; i < num; i++)
{
new_array[i] = new_array();
cout << "Index: " << i << ", random number: " << minimum << endl;
}
return 0;
}
void minimum(int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] minimum)
minimum = new_array[i];
cout << "Maximum value: " << minimum << endl;
}
void maximum (int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] > maximum)
maximum = new_array[i];
cout << "Maximum value: " << maximum << endl;
return 0;
}
void median(int new_array[], int num)
{
//CALCULATE THE MEDIAN (middle number)
if(num % 2 != 0){// is the # of elements odd?
int temp = ((num+1)/2)-1;
cout << "The median is " << new_array[temp] << endl;
}
else{// then it's even! :)
cout << "The median is "<< new_array[(num/2)-1]<<new_array[num/2]< endl;
}
mean(new_array, num);
}
void sort(int new_array[], int num)
{
//ARRANGE VALUES
for(int x=0; x<num; x++){
for(int y=0; y<num-1; y++){
if(new_array[y]>new_array[y+1]){
int temp = new_array[y+1];
new_array[y+1] = new_array[y];
new_array[y] = temp;
}
}
}
cout << "List: ";
for(int i =0; i<num; i++){
cout << new_array[i] << " ";
}
cout << "\n";
median(new_array, num);
}
void average_(int new_array[], int nums)
{
float sum;
for (unsigned int i = 0; i < 20; ++i)
{
sum+=num;
}
cout << "Average value: " << average_/num << endl;
}
Please tell the necessary corrections
You have a ways to go, your code does not do any of the things you want yet. However, you mentioned that you are a beginner so I fixed your code and set up a basic structure of how to get going. I left comments on what I changed and what you need to do. That being said, I don't know what you mean by "Do a binary search on the 15th element"
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int ra()
{
// You wanted a number between 0 and 999 inclusive so do not add 1
// Instead do a modulus of 1000
int r = rand() % 1000;
return r;
}
int main ()
{
// Do this to get different random numbers each time you run your program
srand(time(NULL));
// You have to call ra as a function. Do this by writing: ra()
// Here I am storing 20 random numbers in an array
int nums[20];
for (unsigned int i = 0; i < 20; ++i)
{
nums[i] = ra();
cout << "Index: " << i << ", random number: " << nums[i] << endl;
}
// Iterate to find the minimum number
int minimum = nums[0];
for (unsigned int i = 1; i < 20; ++i)
if (nums[i] < minimum)
minimum = nums[i];
cout << "Minimum value: " << minimum << endl;
// TODO: Find the maximum in basically the same way
// TODO: Find the average by summing all numbers then dividing by 20
// TODO: Find the median by sorting nums and taking the average of the two center elements
// TODO: etc.
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int r;
int ra;
int i=0;
int ra(){
r = (rand() % 999) + 1;
return r;
}
int main ()
{
int random_;
srand((int)time(0));
while (i++ < 20)
{
random_ = r;
cout<< random_<<endl;
}
return 0;
}
Here is what I have come up with so far... I am so close with literally 1 error left for it to compile.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
const int SIZE = 3;
bool equals(const int m1[][SIZE], const int m2[][SIZE])
{
bool identical = true;
for (int i=0; i < SIZE && identical; i++ )
{
if (m1[i] != m2[i]){
identical = false;
}
}
return identical = true;
}
void printArray(const int m1[], int size)
{
for (int i = 0; i < size; i++)
cout << m1[i] << " ";
}
void printArray2(const int m2[], int size) //not sure if I need this 2nd
{ //void
for (int i = 0; i < size; i++)
cout << m2[i] << " ";
}
int main()
{
string input1, input2;
int const SIZE = 3;
double inputnumber;
int m2[SIZE];
int m1[SIZE];
cout << "Please enter the first array: " << endl;
getline(cin, input1);
stringstream ss (input1);
ss >> inputnumber;
cout << "Please enter the second array: " << endl;
getline(cin, input2);
stringstream si (input2);
si>>inputnumber;
for (int i=0; i< inputnumber ; ++i) {
ss >> m1[i];}
if (equals(m1, SIZE)){
cout << "The two arrays are identical ! ";
}
else{
cout << "The two arrays are NOT identical !";
}
cout << endl;
return 0;
}
Or at least I think that I am close... any help is much appreciated.
My current error is coming up on the IF statement in the main function. I could have more mistakes as I am very very new to C++. Like I said please help me out if you can.
If you just want code here it is , but if you want to practice I recommend you to implement error checking(incorrect format) in this code and to change the loops in my code into functions.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string inp;
cout<<"Please enter an array of numbers in the following form\n"
"(where N's are any numbers) :\n"
"[N N N\nN N N\nN N N"<<endl;
double m1[3][3],m2[3][3];
for(short i=0;i<3;i++){
cout<<"> ";
if(i==0) cout<<"[ ";
getline(cin,inp);
stringstream inps(inp);
for(short j=0;j<3;j++){
inps>>m1[i][j];
}
}// Get the first array
cout<<"Now enter the second array :\n";
for(short i=0;i<3;i++){
cout<<"> ";
if(i==0) cout<<"[ ";
getline(cin,inp);
stringstream inps(inp);
for(short j=0;j<3;j++){
inps>>m2[i][j];
}
}// Get the second one
bool not_equal=false;
for(short i=0; i<3 && !not_equal ;i++)
for(short j=0; j<3 && !not_equal ;j++)
if(m1[i][j]!=m2[i][j])
not_equal=true;// Test equality
if(not_equal)
cout<<"The two arrays you entered are not equal !!"<<endl;
else
cout<<"The two arrays you entered are EQUAL ."<<endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int size = 3;
int m2[size][size];
int m1[size][size];
cout << "Please enter the first array: " << endl;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
cin >> m1[i][j];
}
}
cout << "Please enter the second array: " << endl;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
cin >> m2[i][j];
}
}
int flag=1;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
if(m2[i][j]!=m1[i][j])
{
flag=0;
}
}
}
if(flag==1)
{
cout <<"SAME"<<endl;
}
else if(flag==0)
{
cout <<"NOT SAME"<<endl;
}
return 0;
}