Counting the frequency of an elements in an array - c++

Hello I am currently stuck on a homework problem as I have no idea how exactly to approach the problem.
Write a program that reads in a list of integers into an array with base type
int. Provide the facility to either read this array from the keyboard or
from a file, at the user’s option. If the user chooses file input, the program
should request a file name. You may assume that there are fewer than 50
entries in the array. Your program determines how many entries there are.
The output is to be a two-column list. The first column is a list of the distinct
array elements; the second column is the count of the number of
occurrences of each element. The list should be sorted on entries in the
first column, largest to smallest.
So I were to enter: 1, 2, 1, 10, 15, 12, 2, 10, 10
The program should output something like:
List Frequency
1-----2
2-----2
10----3
15----1
I am able to sort the numbers but don't know how I would go about comparing the numbers in the array.
#include <iostream>//Input/Output Library
#include <cstdlib>
#include <iomanip>
using namespace std;//Namespace of the System Libraries
//Global Constants
const int MAX = 10;
//Function Prototypes
void input(int array[], int size);
void sort(int array[],int size);
int main(int argc, char** argv){
//Declare Variable
int array[MAX];
int size = MAX;
//Input Data
input(array, size);
sort(array, size);
cout<<"\nSort Frequency\n";
for(int i = 0; i<size; i++){
cout<<array[i]<<endl;
}
return 0;
}
void input(int a[], int size){
cout<<"Enter "<<size<<" numbers for the array: \n";
for(int i=0; i<size; i++){
cin>>a[i];
}
}
void sort(int a[],int n){
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(a[i]>a[j]){
a[i]=a[i]^a[j];
a[j]=a[i]^a[j];
a[i]=a[i]^a[j];
}
}
}
}

In addition to #stryku's answer since you only want to print frequencies, you don't even need to create the v vector:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <map>
int main() {
std::map<int, size_t> counts;
std::for_each(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), [&counts](int k) {
++counts[k];
});
for(const auto &pair : counts)
std::cout<<pair.first <<" "<< pair.second<<"\n";
return 0;
}

Here you go (:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <map>
int main() {
std::vector<int> v;
std::map<int, size_t> counts;
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(v));
for(const auto &number : v)
++counts[number];
for(const auto &pair : counts)
std::cout<<pair.first <<" "<< pair.second<<"\n";
return 0;
}
I think your teacher will be surprised if you would explain it to him

Related

how to find summation of all elements of array c++

I'm new to c++ but long story short , i want to write a c++ program that will accept input from user through an array and it will sum each array element input
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main() {
int array[100];
int sum;
for(int i=0; i<100; i++){
cout<<"Insert element "<<i<<": ";
cin>>array[i];
sum = array[i]+ //summ with the next array input;
cout<<sum;
}
return 0;
}
means that if i enter any integer the program should be able to give the summation of the inputs in sequence from the first input to the last input
C++ standard library already has a function to do this which is std::accumulate:
#include <iostream>
#include <numeric>
int main() {
int array[5] = {1,2,3,4,5};
int total = std::accumulate(std::begin(array), std::end(array), 0);
return 0;
}
If you plan to use not a full array you should use std::begin(array), std::begin(array) + amount as ranges.
initialize your sum var to 0 initially and write sum+=array[i] instead of what you have written, there is also a limitation in this program as value of sum after all user input should be <=10^9 as int datatype store no. approximately upto 10^9 so take note of this fact also. Write cout<<sum<<endl; instead to be able to distinguish till previous input sum to the new input sum.
Hope this will help.
You can use a do while loop:
#include<iostream>
#include<string>
#include<math.h>
int main()
{
int array[100];
int sum=0;
int i=0;
std::cout<<"Insert element"<<" "<<i<<": ";
std::cin>>array[i];
do
{
sum=sum+array[i];
std::cout<<sum<<std::endl;
i++;
std::cout<<"Insert element"<<" "<<i<<": ";
}while(std::cin>>array[i]);
return 0;
}
If all you want is the sum then just compute the sum. No need to store anything:
#include <iostream>
#include <string>
#include <math.h>
int main() {
int sum = 0;
for(int i=0; i<100; i++){
std::cout << "Insert element " << i << ": ";
int t;
std::cin >> t;
sum += t
std::cout << sum;
}
}

Generating a sequence of different numbers

I am trying to generate a sequence of 6 random numbers with all the numbers being different from each other(no repetition of the numbers). But when I try to test whether I have successfully generated those numbers or not by trying to print them out, the code compiles successfully but nothing appears on the screen. Something seems to be wrong with my use of the function erase() because once I remove it the code produce some output although not what I am looking for.
#include<bits/stdc++.h>
#include<time.h>
using namespace std;
int main(void)
{
srand(time(NULL));
vector<int>v;
vector<int>V;
int arr[6];
int i,j;
for(i=1;i<=6;i++)
{
V.push_back(i);
}
for(int i=0;i<6;i++)
{
cout<<V[i]<<" ";
}
for(int i=0;i<6;i++)
{
int n=rand()%6;
v.push_back(V[n]);
V.erase(V.begin()+n);
}
cout<<endl;
for(int i=0;i<6;i++)
{
cout<<V[i]<<" ";
}
return 0;
}
You are using a wrong algorithm:
Generate six random numbers
If there are some which are equal, do something.
This is better:
Make a full list of all possible numbers.
Take random a number out of that list and remove it from the list. Do this six times.
You should use std::shuffle to re-order your numbers
#include <vector>
#include <iostream>
#include <random>
#include <algorithm>
#include <numeric>
void print_numbers(const std::vector<int> & numbers) {
for (int number : numbers) {
std::cout << number << " ";
}
std::cout << std::endl;
}
int main() {
std::vector numbers(6);
std::iota(numbers.begin(), numbers.end(), 1);
print_numbers(numbers);
std::random_device rd; // ok for small quantities like this, generally prefer a std::default_random_engine with some seed
std::shuffle(numbers.begin(), numbers.end(), rd);
print_numbers(numbers);
}

How to insert the range of numbers to an array by iterating through it?

I am making a program, in which I need to iterate the numbers, starting from 1 to num then put the value of that array {1...num} to a variable that can be called in the for loop.
This is where I am at.
int main()
{
int num = 0;
cin >> num;
for (int i = 1; i <= num; i++)
{
procnum[i];
}
}
I need procnum[num] to have a value like ...
int procnum[num] = {1,2,3...num};
If you can use std::vector and std::iota, this is just two line code.
No need to for(index) loop the array. See live example here
#include <vector> // std::vector
#include <numeric> // std::iota
std::vector<int> procnum(some_size);
std::iota(procnum.begin(), procnum.end(), 1);
In C++11, no need to even write a loop, unless you need to do error checking (e.g. check that reading input succeeded, or that the input value is valid).
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
int main()
{
int size;
std::cin >> size;
std::vector<int> procnum(size);
std::iota(procnum.begin(), procnum.end(), 1); // starting value is 1
// output vector to demonstrate it is populated
std::copy(procnum.begin(), procnum.end(), std::ostream_iterator<int>(std::cout," ");
std::cout << "\n";
}
Before C++11, there was no algorithm std::iota(), but it is possible to use std::generate() and a simple functor to achieve the same effect.
you can use std::vector to create dynamic arrays:
#include <iostream>
#include <vector>
int main() {
int size;
std::cin >> size;
std::vector<int> procnum(size);
for (int i = 0; i < size; ++i) {
procnum[i] = i + 1;
}
}
you shouldn't use namespace std; - read here why.

How to get largest value after leaving one array value?

i am currently having problem getting largest values from an array, here is my code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10],max=0,j,secondbig=0;
for(int i=0;i<10;i++)
{
cin>>a[i];
}
max = a[0];
for(int i=0;i<10;i++)
{
if(a[i]>max){
max=a[i];
j=i;
}
}
secondbig=a[10-j-1];
for(int i=0;i<10;i++)
{
if(secondbig <a[i] && j != i)
secondbig =a[i];
}
cout<<max<<"\n"<<secondbig;
return 0;
}
What i want to do is to first get maximum value from an array and then leave one array value and then get second largest value and same for third largest value, for example :
200
100
50
300
400
500
600
700
800
900
If in the above test values 900 is the largest value then the subsequent second and third largest value should be 700 and 500, is there anyway to do that?
maybe you can sort the array
int *pbeg = begin(a);
int *pend = end(a);
sort(pbeg, pend);
this will sort all elements in the range[pbeg, pend) with operator <,
or sort all elements by using the binary predicate
Given your original code, I presume this is in the style of what you were attempting. it will retrun the three highest vaule. Notice that you only needed to create a loop to repeat the inital computation. You want the max remaining value less than the prior max value.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <limits>
using namespace std;
int main()
{
int a[10], max, prior_max = numeric_limits<int>::max();
for(int i=0;i<10;i++)
{
cin>>a[i];
}
for( int j = 0; j<3; j++){
max = numeric_limits<int>::min();
for(int i=0;i<10;i++)
{
if(a[i]>max && a[i]<prior_max){
max=a[i];
}
}
cout << max << endl;
prior_max = max;
}
return 0;
}
Assuming that you're happy to get the values in place, I'd use a vector.
std::sort(std::begin(a), std::end(a), std::greater<int>());
then print or copy the first n elements of the array (assuming n is no more than your array size, 10). They will be in reverse order, but that can be easily corrected.
As per your follow on question, If you want to list all the max values, change the j<3 to j<10. If you want the numeric sum of the max values that you have extracted from the array, you need to add one more variable:
int a[10], total, max, prior_max = numeric_limits<int>::max();
then within the outer loop, place at the end of the inner loop this statement:
total += max;
Then after the execution of the loops are complete, you can print out the total or otherwise use it. as in:
cout << 'Total: ' << total << endl;

Find in array the biggest multiple and write it vica versa

I was given a task:
it is given an array of five numbers
First - Find all numbers that are multiples of four
Second - Find the biggest of them and write it vice versa.
I have written a code.
#include <iostream>
#include <iomanip>
using namespace std;
#define size 12
int main()
{
int new_max=0;
int a1, a2;
int i=0, j=0;
int a, b, c=0;
int u[size]={38,12,36,45,16,46,14,19,54,53,95, 98};
int max=0;
cout<<"Array: \n";
for(i=0; i<size; i++)
cout<<u[i]<<" \n";
for (int i=0; i<size; i++)
{
if (u[i]%4==0)
{
cout<<"array "<<u[i]<<" \n";
for (int j=0; j<size; j++)
{
if(max<u[i])
{
max=u[i];
}}}}
cout<<"max "<<max<<endl;
while(max > 0)
{
new_max = new_max*10 + ( max % 10);
max = max/10;
}
cout << new_max << endl;
return 0;
}
#include <iostream>
#include <algorithm>
#include <string>
#include <array>
int main() {
std::array<int, 5> input = { 36, 12, 38, 45, 16 };
auto validRangeEnd = std::remove_if(std::begin(input),
std::end(input),
[](int i){ return i % 4 != 0; });
// Now std::begin(input) -> validRangeEnd contain the ones divisible by 4
auto max = std::max_element(std::begin(input), validRangeEnd);
// Max contains the max number from the filtered range
auto stringMax = std::to_string(*max);
std::reverse(std::begin(stringMax), std::end(stringMax));
// Reverse reverses the max number
std::cout << stringMax;
}
By no means optimal but I feel it's useful for educational purposes :).
(Both remove_if and max_elements do a pass so I'll re-examine some stuff that I don't need to but this is a good algorithmic representation of the problem anyway. Also, no loops, look! :))