How to end a user input array - c++

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;
}

Related

How do I detect hitting enter twice to let user exit from populating array with for loop?

I have to let user fill an array with 0-500 values, and at any moment they can exit entering the array with two consecutive empty value inputs (hitting enter twice).
Then the array displays, then it sorts itself, and finally displays again.
I have no idea how to capture enter twice in a row to exit the loop.
The best I can do to help communicate what I am doing, I used getch(); which I am pretty sure my teacher would not like since it isn't standard.
I've tried cin.peek and cin.get but if there is nothing in the stream it always waits for enter which I don't want happening.
I found getch(); and it basically bypasses the problem I am having. I need to make this program operate the same way but using something that is in the c++ standard. Hitting enter after every entry is fine, but I need to detect an empty line and then go into a state where I can detect another one. If it detects one empty line I need to be able to resume entering values.
Here is a somewhat working version with getch(); of what I am going for.
#include <iostream>
#include <conio.h>
using std::cin;
using std::cout;
using std::endl;
const int ARRAY = 500;
int GetUserArray(int b[ARRAY]);
void DisplayVals(int ArrayofValues[ARRAY], int &x);
void SortArray(int ArrayofValues[ARRAY], int& x);
int main()
{
int UserArray[ARRAY]= {0};
int NumberofValues = 0;
//User Populates Array, catches number of entries with return
NumberofValues = GetUserArray(UserArray);
//Displays the NON-SORTED array
DisplayVals(UserArray, NumberofValues);
//Sorts Array
SortArray(UserArray, NumberofValues);
//Displays the SORTED array
DisplayVals(UserArray, NumberofValues);
return 0;
}
int GetUserArray(int UserArray[ARRAY])
{
int howmany = 0;
int input = 0;
//ASCII code for enter key is 13 '\n'
int x = 0;
cout << "Please enter an integer values: ";
for (int i = 0; i < ARRAY; i++)
{
input = _getche();
if (input == 13)
{
cout << endl;
cout << "Please enter an integer value: ";
input = _getche();
if (input == 13)
{
i += 499;
cout << endl;
cout << endl;
cout << "Exiting...";
}
}
UserArray[i] = input;
howmany++;
}
return howmany;
}
void DisplayVals(int ArrayofValues[ARRAY], int &x)
{
cout << '\n' << endl;
for (int i = 0; i < x ; i++)
{
char Display = 0;
Display = ArrayofValues[i];
cout << Display << ' ';
}
cout << endl;
}
void SortArray(int ArrayofValues[ARRAY], int& x)
{
bool sorted = false;
for (int pass = 0; pass < x; pass++)
{
for (int i = 1; i < (x - pass - 1); i++)
{
if ((ArrayofValues[i - 1]) < ArrayofValues[i])
{
int temp = ArrayofValues[i - 1];
ArrayofValues[i - 1] = ArrayofValues[i];
ArrayofValues[i] = temp;
}
}
}
}
Note: ASCII value of \n is 10.
Following is the tested and working code:
int GetUserArray(int UserArray[ARRAY]) {
int input = 0;
int exit_flag = 0;
int howmany = 0;
cout << "Please enter an integer values: ";
for (int i = 0; i < ARRAY; i++) {
input = cin.get(); //Stores ASCII value inside input
if(input==10){
if(exit_flag){
i+=ARRAY; // You should not hard-code any values.
cout<<"Exiting";
}
exit_flag = 1;
--i; //If you don't want to skip an index in case of Single Enter.
continue;
}
else{
exit_flag=0;
UserArray[i] = input-'0'; //Converting ASCII to INT.
howmany++;
cin.ignore(); //Clearing the input buffer as we have pressed 'Enter'.
}
}
return howmany;
}
Thank you.

Finding Max, Min and Mode in c++

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;
}

Creating a function to find duplicates in array without sorting C++

I've been working on a lottery checking program. The goal is to create a function that finds duplicates and allows the user to choose another number in the case of userTicket, and generate another random number in case of winningNums. So this function must be reusable between the two, or with any array for the matter. I am not familiar with sorting and scanning through the array just yet. I have created a nested for loop to go through each index and compare the two between [i] and [j]. My function only works on the first number for some reason. Any ideas are greatly appreciated.
void getLottoPicks(int userArray[])
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for (int i = 0; i < NUMS; i++)
{
cout << "selection #" << i + 1 << ":";
cin >> userArray[i];
cin.ignore();
if (noDuplicates(userArray) == true)
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> userArray[i];
}
}
}
void genWinNums(int winArray[])
{
srand((int)time(NULL));
for (int i = 0; i < NUMS; i++)
{
winArray[i] = rand() % 40 + 1;
if (noDuplicates(winArray) == true)
{
winArray[i] = rand() % 40 + 1;
}
}
}
bool noDuplicates(int dupArray[])
{
int temp = 0;
for (int i = 0; i < NUMS; i++)
{
//temp += dupArray[i];
for (int j = 0; j < i; j++)
{
if (dupArray[i] == dupArray[j])
{
return true;
}
else
{
return false;
}
}
}
}
You can use std::set, it's faster and much less code
void getLottoPicks(std::set<int> userArray)
{
cout << "Please enter your 7 lotto number picks between 1 and 40.\n";
for (int i = 0; i < NUMS; i++)
{
cout << "selection #" << i + 1 << ":";
int num;
cin >> num;
cin.ignore();
// while the num is already in the set
while (userArray.find(num) != userArray.end())
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> num;
}
}
}
In both cases your calls to noDuplicates() are nested inside the loops which are constructing the array that you pass to noDuplicates(). That won't work. First you need to construct the array, and once you are done constructing it, then you pass it to noDuplicates().

How do you get cin to only accept numbers from user input? [duplicate]

This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 6 years ago.
So the requirements for this program is to be able to increment arrays of the same size (size from 5 to 15 indexes) and increment each element in the array by one using for and while loops. The last task is to take values from the first array and put them in reverse order and assign them to the second array.
So everything works as normal, and the program rejects invalid inputs and does not go into an infinite loop. However, the program accepts some inputs that are not wanted.
For example, I would input something like '12 a' or '7 asdfkla;j lasnfg jasklgn asfg' and it would go through. It is interesting too because the code registers only 12 or 7 and completely ignores the rest. I think it is because once it hits a non-integer character, it would stop ignore the rest.
Why is it ignoring the rest of the input? And is there a way to catch this error from going through?
Also, if you see anything that catches your eye, feel free to critique c: I am always looking to improving.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int x;
int j = 0;
bool not_valid = true;
system("color f");
cout << "Program will ask for an input for the size of an array.\n"
<< "With the array size defined, program will generate semi-\n"
<< "true random integers from 0 to 8. First array will then\n"
<< "be assigned to the second in reverse (descending) order.\n\n";
do {
cout << "Enter array size (0 - 15): ";
cin >> x;
if (x >= 5 && x <= 15) {
not_valid = false;
cout << "\nArray size: " << x << endl;
}
else {
cout << "Invalid input.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (not_valid);
int *arr0;
int *arr1;
arr0 = new int[x];
arr1 = new int[x];
for (int i = 0; i < x; i++) {
arr0[i] = rand() % 9;
}
for (int i = 0; i < x; i++) {
arr1[i] = rand() % 9;
}
cout << "\nARRAY 0 (unmodified, for):\n";
for (int i = 0; i < x; i++) {
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 0 (modified, for):\n";
for (int i = 0; i < x; i++) {
arr0[i]++;
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 1 (unmodified, while):\n";
for (int i = 0; i < x; i++) {
cout << arr1[i] << "\t";
}
cout << "\n\nARRAY 1 (modified, while):\n";
while (j < x) {
arr1[j]++;
cout << arr1[j] << "\t";
j++;
}
int second = x - 1;
for (int i = 0; i < x; i++) {
arr1[second] = arr0[i];
second--;
}
j = 0;
cout << "\n\nARRAY 1 (array 0, descending):\n";
while (j < x) {
cout << arr1[j] << "\t";
j++;
}
cout << endl << endl;
system("pause");
return 0;
}
Take input in string and then check if it's a number or not.
Example:
#include<iostream>
#include<sstream>
#include <string>
using namespace std;
int main()
{
string line;
int n;
bool flag=true;
do
{
cout << "Input: ";
getline(cin, line);
stringstream ss(line);
if (ss >> n)
{
if (ss.eof())
{
flag = false;
}
else
{
cout << "Invalid Input." << endl;
}
}
}while (flag);
cout << "Yo did it !";
}

Dynamic arrays using float

I've got a small task I need to complete and I'm rather confused. This task has 3 parts to it which are:
Write a program that dynamically allocates a float array of a size specified by a user (currently working on - if anyone could check my code for this it would be appreciated.
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
Program should print what was saved into the array, the sum, and the average value in the array, and exit.
As you could tell I'm new to C++ and coding in general so please spell it out for me wherever possible. It is mandatory that I am using pointers so I'm afraid I can't change that.
#include <iostream>
using namespace std;
int main()
{
int length;
cout << “Please enter the length of the array: “;
cin >> length;
float * dArray = new float [length];
for (int i = 0; i < length; i++)
{
cin >> dArray[i] = i;
for (int i = 0; i < length; i++)
{
cout << dArray[i] << “ “;
}
cout << ‘/n’;
int sum = 0;
for (int i=0; i < length; i++)
{
sum +=dArray[i];
avg =sum/length;
cout << “Sum is “ << sum << “/nAverage is “ << average;
delete [] dArray;
}
return 0;
}
Please explain the 2nd part.
Thanks in advance.
Regarding
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
It means that you have to let the user input the values to that array. What you are doing is giving them values yourself.
What you need to do is change
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
to
for (int i = 0; i < length; i++)
{
cin>>dArray[i];
}
Also Note that length should be an int and not a float.
After completion, this would probably be the code you need ( although I would advice you to do the part of finding the sum and average by yourself and use this code I have posted as reference to check for any mistake, as finding the sum and average for this is really easy )
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
float sum = 0 , avg; // variables to store sum and average
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for (int i = 0; i < length; i++)
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
delete[] dArray;
return 0;
}
EDIT
After getting your comment, I decided to post this new code. ( I am assuming what you meant is that the program should repeat as long as the user wants )
I have done it by using a do while loop.
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
char a; // a variable to store the user choice
do
{
float sum = 0 , avg; // variables to store sum and average
cout << "\nPlease enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for ( int i = 0; i < length; i++ )
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++ ) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
cout << "\n\nDo you want to try again ( y/n ) ?\n";
cin >> a;
delete[] dArray;
}while( a =='Y' || a == 'y' ); // The do while loop repeats as long as the character entered is Y or y
return 0;
}
Well, hope this is what you were looking for, if not, please do notify me with a comment... :)
Just so you know, the new code you have posted doesn't even compile. Here are some of the problems.
cin >> dArray[i] = i;
You don't need to use = i here. Just cin >> dArray[i] ; is enough.
The next problem is
cout << ‘/n’;
First of all, its \n and not /n. You also need to enclose it in double quotes and not single quotes. That is cout << "\n";
Next one, you have not defined the variable avg . Also note that you have also used an undefined variable average, which I assume you meant avg.
Now here's one of the main problems , You have not closed the curly brackets you opened. You open the brackets for for loops, but forget to close it. I'm leaving that part to you as you need to learn that part yourself by trying.
Now Here's one problem I don't understand, you have used “ “, which is somehow not the same as " ". I don't know if it's something wrong with my computer, or if it's a totally different symbol. My compiler couldn't recognize it. If its not causing any trouble on your end, then don't mind it.
Well, this sums up the problems I noticed in your code ( the problems that I noticed ).
Your issues are too simple for us to just give you the answers, but I've commented your code with suggestions on how to solve your problem:
#include <iostream>
using namespace std;
int main()
{
float length; //it doesn't make sense for something to be of a float length
//should be size_t instead
cout << "Please enter the length of the array: ";
cin >> length;
float *dArray = new float[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i; //this line is incorrect
//how should we read the data into this array?
//we've used cin before
}
for (int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
cout << '\n';
//now we've output the array, just need to output the sum and average value
int sum = 0;
for (int i=0; i < length; i++)
{
sum += //what should go here?
}
int average = //how should we calculate the average?
cout << "Sum is " << sum << "\nAverage is " << average;
delete[] dArray;
return 0;
}