Breaking a loop when entering a specific number? - c++

How would I break a loop when the user enters 0 after entering a series of numbers? For this project I am trying to read the amount of time a number comes up.
Example: if the user enter 1 5 6 9 8 7 1 3 5
then the program would go
1 appeared 2 times
5 appeared 2 times
6 appeared 1 time
... and so on,
Another question I have is, how do I only print the elements that the user inputs instead of printing all elements?
I really appreciate any help. Thanks!
#include <iostream>
using namespace std;
void nums(int[]);
int main() {
cout << "Enter the however much numbers between 1-100 that you want, when you are done type 0 to finish: " << endl;
int myarray[100] = { 0 };
for (int i = 0; i < 100; i++) {
cin >> myarray[i];
if (myarray[i] == 0) {
break;
}
}
nums(myarray);
system("pause");
return 0;
}
void nums(int myarray[]) {
for (int i = 0; i < myarray[i]; i++) {
cout << myarray[i] << " "; //This code only prints out all the elements if the user inputs numbers in order. How do I get it to print out the elements the user inputs?
}
}

I used the indexes of each element to hold actual value and and the count as value of that index, hope it help :
#include <iostream>
#include <vector>
int main() {
//create a vector with size 100
std::vector<int> numberVector(100);
//init all elements of vector to 0
std::fill(numberVector.begin(), numberVector.end(), 0);
int value;
std::cout << "Enter the however much numbers between 1-100 that you want, when you are done type 0 to finish: " << std::endl;
while (true) {
std::cin >> value;
//braek if 0
if (value == 0) {
break;
}
//++ the value of given index
++numberVector.at(value);
}
//for all elements of the vector
for (auto iter = numberVector.begin(); iter != numberVector.end(); ++iter) {
//if the count of number is more than 0 (the number entered)
if (*iter > 0) {
//print the index and count
std::cout << iter - numberVector.begin() << " appeared " << *iter << " times\n";
}
}
//wait for some key to be pressed
system("pause");
return 0;
}
EDIT : If your are not using c++1z, replace auto iter with std::vector<int>::iterator iter

Related

How to echo input within a void function and do-while loop C++

I need some advice on how to echo the input from the user. A bit of background on the program that this is needed first. I created this program so that it asks the user how many values they would like to enter and then they enter the number in positive integers. Then the program computes to figure out if the numbers are even, odd, or zero and displays said information. I'm stuck on how I can create something that can output all of the enter values on the same line. For example, if the user chooses to enter in 4 values, being 1,2,3, and 4, with my current program it will read, Enter a number on one line and the next would be the number 1. Then it would ask to enter a number again and on another line the number 2. When I want it to read, The values you entered are 1,2,3,4. I'm confused as to how it works to display all the input on one line with a call by reference. Any advice or explanation would be greatly appreciated!
Code below
#include<iostream>
using namespace std;
void initialize(); //Function declarations
void get_number(int x);
void classify_number(int, int& zero_count, int& even_count, int& odd_count);
void print_results();
int N; //The number of values that the user wants to enter
//variables declared so that all functions can access it
int even_count;
int odd_count;
int zero_count;
int main()
{
cout << "Enter number of values to be read, then press return.\n"; //Prompting the user for how many values they will want to input
cin >> N;
get_number(N);
return 0;
}
void initialize() //This function is making sure that all the variables being used are initialized
{
even_count = 0;
odd_count = 0;
zero_count = 0;
}
void get_number(int N) //This function is getting the input from the user and then calling upon the previous function
{
int count = 0;
int x;
initialize(); //Calling upon the previous function to uses the variables
do {
cout << "Enter a positive whole number, then press return.\n";
cin >> x; //The number the user enters
//call the funtion and increment their count
classify_number(x, zero_count, even_count, odd_count); //Calling upon the function classify to update
count++;
} while (count < N);
//then print the count
print_results(); //Calling upon the print function
}
void classify_number(int x, int& zero_count, int& even_count, int& odd_count) //This function determines if it's an even,odd, or zero
{
if (x == 0)
zero_count++;
else if (x % 2 == 0)
even_count++;
else
odd_count++;
}
void print_results() //This is printing the results on the screen of the number of even, odds, and zeros.
{
cout << "There are " << even_count << " number of evens.\n";
cout << "There are " << zero_count << " number of zeros.\n";
cout << "There are " << odd_count << " number of odds.\n";
}
I believe that this much code will be sufficient :
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::size_t n;
std::cout << "Enter number of elements : ";
std::cin >> n;
std::vector<int> v(n);
std::cout << "Enter the numbers now : ";
for (auto &i : v) std::cin >> i;
std::cout << "The values you entered are : [ ";
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ","));
std::cout << "\b ]\n";
auto odd = std::count_if(v.begin(), v.end(), [](auto i) { return i % 2; });
auto zero = std::count(v.begin(), v.end(), 0);
auto even = v.size() - (odd + zero);
std::cout << "There are " << even << " even number(s).\n"
<< "There are " << zero << " zero(s).\n"
<< "There are " << odd << " odd number(s). \n";
}
Sample Run :
Enter number of elements : 6
Enter the numbers now : 0 1 2 3 4 6
The values you entered are : [ 0,1,2,3,4,6 ]
There are 3 even number(s).
There are 1 zero(s).
There are 2 odd number(s).
Ref. :
std::vector
Range-based for loop
How to print out the contents of a vector?
std::count, std::count_if
You could simply use an array of integers.
#include<iostream>
int main(int argc, char *argv[]){
/* Declare an array great enough to store all possible user values. */
/* Or use dynamic memory allocation when you are more experienced. */
int my_array[16];
int my_array_length = sizeof my_array / sizeof my_array[0];
/* As your code only uses positive integers, we use this information */
/* to our advantage and initialize our array with negative numbers. */
for(int i = 0; i < my_array_length; i++){
my_array[i] = -1;
}
/* Here is your own input program routine. I'll use some example values. */
for(int i = 0; i < my_array_length; i++){
if(i > 4){
break;
}
my_array[i] = i;
}
/* Here is your output program routine. */
for(int i = 0; i < my_array_length; i++){
if(my_array[i] == -1){
break;
}
std::cout << my_array[i] << std::endl;
}
return 0;
}
Or you could just count the amount of inputs in the first place.

Checking for duplicates in an array using for loop

I am trying to check whether there is any duplicate integer in the user input array. The problem is that the validation of the duplicate does not work properly and I have no idea why it is not showing the desired output. Following is the code:
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arr[i];
}
cout << "Array : ";
for(int i = 0; i < length; i++)
{
arrValue = arr[i];
for(int k = i + 1; k < length; k++)
{
if(arr[i] == arr[k])
{
cout << "Duplicate found" << endl;
break;
}
else
{
cout << arrValue << " ";
}
}
}
delete[] arr;
}
Current result (assuming no duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 5 5 5 4 4 4 3 3 2
Expected result (assuming no duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 4 3 2 1
Current result (assuming duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : 5 5 5 5 Duplicate found 4 4 3
Expected result (assuming duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : Duplicate found
I believe my loops is the source to the problem. The current result output 10 times and I do not understand why there will be so many same numbers appearing.
Do note that I am trying to apply the validation using loop only and not from C++ standard library.
The issue in your code is that you are printing out each array element every time a particular element is not matching another element. It seems that you only want to print out whether any duplicate values are found. For this, you can use a bool flag to indicate whether any element is duplicated:
bool found_dup = false;
for(int i = 0; i < length; i++)
for(int k = i + 1; k < length; k++)
if(arr[i] == arr[k])
{
found_dup = true;
break;
}
// else: don't print anything yet
and then at the end print out the array:
if (found_dup)
std::cout << "Duplicate found";
else
for(int i = 0; i < length; i++)
std::cout << arr[i] << " ";
You may achieve the program in a more enhanced way (where you don't need to define the length manually - notice the explanation given as comments in code):
#include <iostream> // for input/output operation
#include <vector> // for dynamic array management
#include <sstream> // to split the user inputs and assign them to the vector
#include <algorithm> // to sort the vector
#include <string> // to work with getline()
// using this statement isn't recommended, but for sake of simplicity
// and avoiding the use of std:: everywhere temporarily (for small programs)
using namespace std;
int main(void) {
vector<int> numbers;
vector<int> duplicates;
string input;
int temp;
// getting the user input as string
cout << "Enter the numbers: ";
getline(cin, input);
stringstream ss(input);
// splitting the user input string into integers and assigning
// them into the vector
while (ss >> temp)
numbers.push_back(temp);
// sorting the vector in increasing order
sort(numbers.begin(), numbers.end());
// getting the unique numbers (which are not repeated)
cout << "Unique numbers: ";
for (size_t i = 0, len = numbers.size(); i < len; i++) {
if (temp == numbers[i])
// if found a duplicate, then push into the 'duplicates' vector
duplicates.push_back(temp);
else
cout << numbers[i] << ' ';
temp = numbers[i];
}
// getting the duplicates
cout << "Total duplicates: ";
for (size_t i = 0, len = duplicates.size(); i < len; i++)
cout << duplicates[i] << ' ';
cout << endl;
return 0;
}
It'll output something like:
Enter the numbers: 1 4 8 9 3 2 3 3 2 1 4 8
Unique numbers: 1 2 3 4 8 9
Total duplicates: 1 2 3 3 4 8
Please change the if condition to something like this.
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arr[i];
}
cout << "Array : ";
for(int i = 0; i < length; i++)
{
arrValue = arr[i];
for(int k = i + 1; k < length; k++)
{
if(arrValue == arr[k]) //change here.
{
cout << "Duplicate found" << endl;
break;
}
else
{
cout << arrValue << " ";
}
}
}
delete[] arr;
}
I would also suggest to use a map data structure. Map allows you to count the frequency of numbers, and thus detect duplicates in linear time.
map<int, int> m; // specify the key-value data-type.
for(int i = 0;i<length;i++)
{
m[arr[i]]++;
}
map<int, int>::iterator it; // an iterator to iterate over the datastructure.
for(it = m.begin();it!=m.end();it++)
{
if(it->second>1) //it->second refers to the value(here, count).
{
cout<<it->first<<" "; //it->first refers to the key.
}
}
Your loops are actually iterating n-1 times for first element, n-2 times for second element etc., where n is the length of your array. This is why for 5 element array you have printed 5 4 times.
But generally, if the purpose is to detect duplicates in the array, this strategy is not the best one. Please note that having exemplary array 4 3 4, with current approach you will correctly detect for the first 4 that the third element is also 4 but once you will move to the third element, it will be marked as ok since it is not checked with the first one element.
You may consider another strategy: create another array of the n size. Then iterate through your original array and for each element check if that element is already in the new array. If you detect the presence, you may raise duplicate event. Otherwise you can add this element to the array.
It doesn't work because you're trying to print the same value everytime you find a different one. I got here a solution with one more array that will store the array. It would work too with just one array.
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
int *noDuplicateArr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
cin >> arr[i];
cout << "Array : ";
bool duplicateFound = false;
int noDuplicateArrLen = 0;
for(int i = 0; i < length && !duplicateFound; i++)
{
arrValue = arr[i];
int k;
for(k = i + 1; k < length; k++)
{
if(arrValue == arr[k])
{
duplicateFound = true;
break;
}
}
if (k == length)
noDuplicateArr[noDuplicateArrLen++] = arrValue;
}
if (duplicateFound)
{
cout << "Duplicate found";
}
else
{
for (int i = 0; i < noDuplicateArrLen; i++)
{
cout << noDuplicateArr[i] << " ";
}
}
delete[] arr;
delete[] noDuplicateArr;
}
Here is the version with just one array:
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
cin >> arr[i];
cout << "Array : ";
bool duplicateFound = false;
int noDuplicateArrLen = 0;
for(int i = 0; i < length && !duplicateFound; i++)
{
arrValue = arr[i];
int k;
for(k = i + 1; k < length; k++)
{
if(arrValue == arr[k])
{
duplicateFound = true;
break;
}
}
if (k == length)
arr[noDuplicateArrLen++] = arrValue;
}
if (duplicateFound)
{
cout << "Duplicate found";
}
else
{
for (int i = 0; i < noDuplicateArrLen; i++)
{
cout << arr[i] << " ";
}
}
delete[] arr;
}

Arrange the array of elements 0, 1, and 2 so that the array places all 0 in the first places, then all 1s and 2 as last

I need to Write a C ++ program that prompts the user to enter 10 integers in the array.
Input numbers are: 0, 1 or 2.
The program should extract the array that is entered on the screen Arrange the array of elements 0, 1, and 2 so that the array places all 0 in the first places, then all 1s
and all 2 as the last.
Arranged array displays on the screen.
Have been struggling over this for few hours now. Im stuck and dont know how to show Output .
Input should be for example 0 0 1 0 1 2 2 2 0 1
Output 0000111222
HOW?
int main ()
{
int t [N], i, ;
cout << "Enter 10 arrays from 0-2" << endl;
cout << "Original array:";
for (i = 0; i <N; i ++)
{
cin >> t [i];
}
if (t [i]> = 0 && t [i] <= 2)
{
cout << "Rearranging elements of array:" << ? << endl;
}
cout << "End of the program!"
return 0;
}
when you do
if (t [i]> = 0 && t [i] <= 2)
i equals N so you access out of the array, and of course that does not sort the array
You do not check if cin >> t[i] success so if the user enter something else than an int all the entries from the current will not be set (they will be 0 in case you use a std::vector)
A first way is to do without taking account the range 0..2, replace int t[n] by std::vector<int> t(N) and use sort(t.begin(), t.end()) to sort your array
The complexity is O(N*log(N)) (here N is 10)
For instance :
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 10
int main ()
{
vector<int> t(N);
size_t i; // size_t the right type for an index
cout << "Enter 10 values in range 0..2" << endl;
for (i = 0; i < N; ++i)
{
for (;;) {
cout << "value #" << i << ':';
if (!(cin >> t[i])) {
cerr << "not a number" << endl;
cin.clear(); // raz error
string s;
cin >> s; // skip bad input
}
else if ((t[i] < 0) || (t[i] > 2))
cerr << "value out of range" << endl;
else
break;
}
}
cout << "Original array:";
for (i = 0; i < N; ++i) cout << ' ' << t[i]; // old way to do
cout << endl;
sort(t.begin(), t.end());
cout << "Sorted array:";
for (auto v : t) cout << ' ' << v; // new way to do
cout << endl;
cout << "End of the program!" << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s.cc
pi#raspberrypi:/tmp $ ./a.out
Enter 10 values in range 0..2
value #0:aze
not a number
value #0:-2
value out of range
value #0:3
value out of range
value #0:2
value #1:0
value #2:1
value #3:2
value #4:0
value #5:2
value #6:1
value #7:0
value #8:0
value #9:1
Original array: 2 0 1 2 0 2 1 0 0 1
Sorted array: 0 0 0 0 1 1 1 2 2 2
End of the program!
A second way considering a range [min .. max] not too large is to count the number of each value then fill the array to respect these counts
The complexity is O(2N) (here N is 10)
For instance :
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define MIN 0
#define MAX 2
#define N 10
int main ()
{
vector<int> t(N);
size_t i; // size_t the right type for an index
cout << "Enter 10 values in range " << MIN << ".." << MAX << endl;
for (i = 0; i < N; ++i)
{
for (;;) {
cout << "value #" << i << ':';
if (!(cin >> t[i])) {
cerr << "not a number" << endl;
cin.clear(); // raz error
string s;
cin >> s; // skip bad input
}
else if ((t[i] < MIN) || (t[i] > MAX))
cerr << "value out of range" << endl;
else
break;
}
}
cout << "Original array:";
for (auto v : t) cout << ' ' << v;
cout << endl;
// count numbers
vector<size_t> counts(MAX - MIN + 1);
for (auto v : t) counts[v - MIN] += 1;
// fill again
i = 0;
for (int r = MIN; r <= MAX; ++r) {
size_t n = counts[r - MIN];
while (n--) t[i++] = r;
}
cout << "Sorted array:";
for (auto v : t) cout << ' ' << v;
cout << endl;
cout << "End of the program!" << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s2.cc
pi#raspberrypi:/tmp $ ./a.out
Enter 10 values in range 0..2
value #0:a
not a number
value #0:3
value out of range
value #0:0
value #1:2
value #2:1
value #3:1
value #4:2
value #5:2
value #6:2
value #7:0
value #8:1
value #9:2
Original array: 0 2 1 1 2 2 2 0 1 2
Sorted array: 0 0 1 1 1 2 2 2 2 2
End of the program!
Specifically for values between 0 and 2 (in fact for 3 possible values) as said in a remark by #PaulMcKenzie you can use the Dutch national flag problem and look at that question : R G B element array swap
The complexity is O(N) (here N is 10)
As a beginner, you may want to try this (this is the simplest solution I could think of without using other libraries):
int main () {
const int size = 10;
int arr[size], temp = 0;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
for (int j = 0; j < size - 1; j++) {
for (int k = 0; k < size - j - 1; k++) {
if(arr[k] > arr[k+1]) {
temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
else
continue;
}
}
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
I hope this helps you.
1st answer is too difficult for me, im only beginner not knowing what im doing yet.
2nd answer is to that direction where it should be right but i need to put in that input cant be more than 2 or less than numeber 0, thats the problem now :D
Im sorry, i just cant get to that point where i understand that syntax.

sort and show the number of digits

I want to my program can sort the inputted integer and compute the number of any integer that inputted and I don't know where should write the cout of c
example
a[9]={2,3,2,6,6,3,5,2,2}
the number of 2 is 4
the number of 3 is 2
the number of 6 is 2
.
.
please fix this code
int main()
{
cout << "please enter the number of digites :" << endl;
int n;
cin>>n;
int a[n];
cout<<"enter numbers :"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
int c;
for(int m=0;m<n;m++)
{
if(a[m]==a[m+1])
c++;
else
c=0;
}
return 0;
}
Read through my solution, I've commented the parts I've changed. I tidied it up a little.
To answer your question: you should print the output (frequency of an integer in array) before you reset the count variable to 1. This will work because we have sorted the array, and will not have to look ahead for more occurrences of the current number.
[EDIT] I also added this above your code:
#include <iostream>
#include <vector>
using namspace std;
Full Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Get input
int n;
cout << "Please enter the number of digits: ";
cin>>n;
vector<int> a;
cout << "Enter " << n << " numbers: " << endl;
for(int i=0;i<n;i++) {
int temp;
cin >> temp;
a.push_back(temp);
}
// Sort input
int i,j;
for (i = 0; i < a.size(); i++) {
for(j = 0; j < a.size()-i-1; j++) {
if(a[j] > a[j+1]) {
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
// If an element is in an array
// we can not have 0 occurrences
// of that element, hence count
// must start at 1
int count = 1;
// Int to count
int current = a[0];
// Ouput if we have reset the count,
// or if it is the last iteration
bool output;
// Loop through array
for (int i = 1; i < a.size(); i++) {
output = false; // Reset output if we have printed
if (a[i] == current) {
// If current int and the element next to it are the same,
// increase the count
count++;
} else {
// If current and next are different,
// we need to show the frequency,
// and then reset count to 1
cout << current << " occurs " << count << " times" << endl;
count = 1;
current = a[i];
}
}
// Output one last time, for last int in sorted set
cout << current << " occurs " << count << " times" << endl;
return 0;
}
If this doesn't help, go and read this page, it is a solution in C, but can be adapted to C++ easily. https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html This will help you understand and write the task. They take you step-by-step through the algorithm.
This is a typical use-case for a std::map. A std::map<char,int> lets you easily count the frequency of charaters (its easier to treat the user input as characters instead of converting it to numbers).
This is basically all you need:
#include <iostream>
#include <iterator>
#include <map>
int main(){
std::istream_iterator<char> it( std::cin );
std::istream_iterator<char> end_of_input;
std::map<char,int> data;
while (it != end_of_input ) data[*(it++)]++;
for (const auto& e : data) std::cout << e.first << " " << e.second << "\n";
}
This is probably a lot at once, so lets go one by one.
std::istream_iterator<char> lets you extract characters from a stream as if you are iterating a container. So the while iteratates std::cin until it reaches the end of the input. Then *(it++) increments the iterator and returns the character extracted from the stream. data[x]++ accesses the value in the map for the key x and increments its value. If there is no value in the map yet for the key, it gets default initialized to 0.
For input: 11223 it prints
1 2
2 2
3 1
Your code has some issues, not sure if I can catch them all...
You are using VLA (variable lenght arrays) here: int a[n];. This is a compiler extension and not standard c++.
You access the array out of bounds. When i == 0 then j goes up to j<n-i-1 == n-1 and then you access a[j+1] == a[n], but the last valid index into the array is n-1. Same problem in the other loop (a[m+1]).
Assuming your sorting works, the last loop almost gives you the number of elements, but not quite, to fix it you can change it to...
int current = a[0];
int counter = 1;
for(int m=1;m<n;m++) {
if(a[m] == current) {
counter++;
} else {
std::cout << current << " appears " << counter << " times" << endl;
counter=1; // note: minimum freq is 1 not 0
current = a[m];
}
}

Find Occurrences in Array

I Have to find the occurrences of every element in array.
So far My code is this
void Occurrences()
{
int numers[10], count = 0, i;
for (i = 0; i < 10; i++)
{
cout << "Enter Number";
cin >> numers[i];
}
for (i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (numers[i] == numers[j])
{
count++;
}
}
cout << numers[i] << " is Occur " << count << " Time in Array" << endl;
count = 0;
}
}
int main()
{
Occurrences();
}
Output is coming multiply same numbers i.e If I entered six 1 and 4 2's. Output is
1 is occur 6 time in array.
1 is occur 6 time in array.
1 is occur 6 time in array.
1 is occur 6 time in array.
1 is occur 6 time in array.
1 is occur 6 time in array.
2 is occur 4 time in array.
2 is occur 4 time in array.
2 is occur 4 time in array.
2 is occur 4 time in array.
But I want output like this:
1 is occur 6 time in array.
2 is occur 4 time in array.
How do I do this?
Since you tagged this C++11, I would use std::unordered_map:
void Occurrences()
{
std::unordered_map<int, int> occurrences;
// enter 10 numbers
for (int i = 0; i < 10; ++i) {
cout << "Enter Number";
int x;
cin >> x;
++occurrences[x]; // increment the count for x
}
// print results
for (const auto& pr : occurrences) {
std::cout << pr.first << " appears " << pr.second << " times." << std::endl;
}
}
Your problem is you're searching for items you've already output. you can skip those items if you sort the array first.
Just to be different, I'm going to tell you how to do this with your existing code, an array, and not a map.
read the values in the array.
sort the array.
enumerate the array, and ignore (but count) any elements matching the previous element. reset the counter when you discover a new element.
thats it.
Example:
#include <iostream>
#include <algorithm>
void Occurrences()
{
int numers[10], i;
for (i = 0; i < 10; ++i)
{
std::cout << "Enter Number";
if (!(std::cin >> numers[i]))
break;
}
// sort the array in ascending order , O(NlogN)
std::sort(numers, numers+i);
for (const int* it = numers; it != numers+i;)
{
unsigned int count = 1;
int value = *it;
for (++it; (it != numers+i) && *it == value; ++count, ++it);
std::cout << value << " occurs " << count << " times." << std::endl;
}
}
int main()
{
Occurrences();
}
Your Sample Run
Enter Number1
Enter Number1
Enter Number1
Enter Number1
Enter Number1
Enter Number1
Enter Number2
Enter Number2
Enter Number2
Enter Number2
1 occurs 6 times.
2 occurs 4 times.
No map required. if you choose to use a map, consider an unordered map (hash table) as it may produce better performance.
Best of luck.
Better store it in a map and display everything later.
void Occurrences()
{
int numers[10],count = 0,i;
std::map<int,int> mapCnt;
for(i =0;i<10;i++)
{
cout<<"Enter Number";
cin>>numers[i];
}
for( i = 0;i<10;i++)
{
for(int j = 0;j<10;j++)
{
if(numers[i] == numers[j])
{
count++;
}
}
mapCnt[numers[i]]=count;
count = 0;
}
// Print the map Here
typedef std::map<int,int>::iterator it_type;
for(it_type iterator = mapCnt.begin(); iterator != mapCnt.end(); iterator++) {
cout << iterator->first << " is Occur " << iterator->second << " Time in Array" << endl;
}
}
Looping through map https://stackoverflow.com/a/4844904/2466168
A variation from maandoo's code if you can process as your read the numbers in:
void Occurrences()
{
int i;
std::map<int,int> mapCnt;
for(i =0;i<10;i++)
{
int num;
cout<<"Enter Number";
cin>>num;
std::map< int, int >::iterator iter( mapCnt.find( num ) );
if( iter != mapCnt.end() )
mapCnt[num] = 1;
else
++( iter->second );
}
// Print the map Here
for( i = 0; i < mapCnt.size(); ++i )
std::cout << mapCnt[i].first << " occurs " << mapCnt[i].second << " times in array\n";
}