sort and show the number of digits - c++

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

Related

get length of an array in C++

int grades[100];
int j = 0;
int len = sizeof(grades)/sizeof(grades[0]);
while (j < len)
{
cout << grades[j] << endl;
j++;
}
I have entered only 5 grades and I want to print only that entered grades then ho can I print that?
I have tried to use length of array but since I have created array of size 100, it is printing all unwanted characters at the end.
I have also used '\0' to get end of array but it is not working.
#include <vector>
std::vector<int> grades;
// add 3 grades
grades.push_back(4);
grades.push_back(1);
grades.push_back(9);
// https://www.cplusplus.com/reference/vector/vector/size/
auto size = grades.size();
Just keep track of the size when you read the numbers:
#include <iostream>
int main()
{
int const max_len = 100;
int arr[max_len];
std::cout << "Enter numbers: ";
int len = 0;
while (len < max_len && std::cin >> arr[len]) {
++len;
}
// you've read `len` numbers.
std::cout << "You've entered " << len << " numbers\n";
for (int i = 0; i != len; ++i) {
std::cout << arr[i] << '\n';
}
}
Your code returns the total number of elements the array can store.
Try this instead:-
#include <iostream>
int main()
{
int sample[10];
int length = 0;
for (int integer : sample)
{
if (integer != NULL)
{
length++;
// If you want to print the element as well -
std::cout << integer << std::endl;
}
}
}
Essentially what it does goes through all of the elements of the array and adds 1 to length if that element is not NULL (NULL means a null pointer, or if you're a beginner, just know it means basically nothing).
You can easily change int to any other type.
Hope it helps :)

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.

write program to display odd and even numbers

im trying to write this code but i couldn't
the q is :
by using for loop, write a program to receive input for any 5 numbers and display the total of even an odd numbers. the output should be as shown below
---------------------------------
Enter any 5 numbers: 0 1 3 2 11
0 is not even number.
total exists even = 1
total exist odd = 3
--------------------------------
and this is what i did:
#include<iostream>
using namespace std;
int main()
{
int i,j=0,c=0;
for(i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>i;
}
if(i==0)
{
cout<< "0 is not even number"<<endl;
}
else if(i%2==0)
{j++;}
else if(i%2 !=0)
{c++;}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Going through your code step by step (notice the changed formatting!):
#include<iostream>
using namespace std; // usually considered bad practice
int main()
{
int i, j=0, c=0;
for(i = 0; i < 5; i++)
{
cout << "enter 5 numbers " << i;
cin >> i; // you are overwriting your loop variable!!!
// how do you think your program will go on if you enter
// e. g. 7 right in the first loop run?
// additionally, you did not check the stream state afterwards
// if user entered something invalid (e. g. S), cin sets the
// fail flag and stops further reading - attemps doing so yield
// 0 (since C++11) or don't modify the variable (before C++11)
}
// this section is outside the loop already!
// so you are only checking the number you read in your loop in the very last run
if(i == 0)
{
cout << "0 is not even number" << endl;
}
else if(i % 2 == 0)
{
j++;
}
// this check is redundant: it is the complement to your previous
// check, so if the first went wrong, the second cannot be false any more
// (compare: you did not check for i != 0 either before doing the modulo check)
else /* if(i % 2 != 0) */
{
c++;
}
cout << "total exists even: " << j << endl;
cout << "total exists odd: " << c << endl;
return 0;
}
Changed code:
#include<iostream>
int main()
{
// several serious coding guide lines mandate: only one variable per line:
unsigned int odd = 0;
unsigned int even = 0;
// I used unsigned int here, negative counts are just meaningless...
// I'm consequent in these matters, but range of (signed) int suffices anyway,
// so you can use either one...
// C++ is not C (prior to C99) - keep scope of variables as local as possible
// (loop counter declared within for header, local variable within body)
for(unsigned int i = 0; i < 5u; i++) // (unsigned? see above)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n; // separate variable!
if(!(std::cin >> n))
{
// some appropriate error handling!!! e. g.:
std::cout << "invalid value entered";
return -1;
}
// this now resides INSIDE the for loop
if(n == 0)
{
cout << "0 is not even number" << endl;
}
else
{
// this is an ALTERNATIVE calculation
n %= 2; // gets either 0 or 1...
odd += n;
even += 1 - n;
// (I personally prefer avoiding conditional branches but you *can*,
// of course, stay with the if/else you had before, too...
// - just don't check the complement as shown above)
}
}
cout << "total exists even: " << even << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
About the unsigned: Sometimes these are of advantage:
void f(int n) { /* need to check for both 0 <= n && n <= max! */ }
void f(unsigned int n) { /* n <= max suffices */ }
but sometimes one has to handle them with care:
for(unsigned int n = 7; n >= 0; --n) { /* ... */ } // endless loop!!!
for(unsigned int n = 7; n-- >= 0;) { /* ... */ } // correct variant
(the first one would have worked with signed int, but it is not the fault of the unsigned type, but the programmer's fault who did not chose the right type for what he or she intended...).
Just for completeness: Assuming we could drop the mathically incorrect statement that zero wasn't even, we could have it even much simpler:
unsigned int constexpr LoopRuns = 5u;
int main()
{
unsigned int odd = 0; // just one single variable...
for(unsigned int i = 0; i < LoopRuns; i++)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n;
if(!(std::cin >> n))
{ /* ... */ }
odd += n %= 2;
}
// one single difference instead of five additions...
cout << "total exists even: " << LoopRuns - odd << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
This program will help you out.
#include <iostream>
int main () {
int num[5], even = 0, odd = 0;
bool hasZero = false;
std::cout << "Enter 5 numbers:"
for (int i = 0; i < 5; i++) {
std::cin >> num[i];
}
for (int i = 0; i < 5; i++) {
if (num[i] == 0) { // Checking if the current number is zero
hasZero = true;
} else if (num[i] % 2 == 0 ) { // Checking if the current number is even
++even;
} else { // If the number is not even, then it must be odd
++odd;
}
}
if (hasZero) { // If the input has zero then print following statement
std::cout << "0 is not an even number" << std::endl;
}
std::cout << "Total even count: " << even << std::endl;
std::cout << "Total odd count: " << odd << std::endl;
return 0;
}
If you are unable to understand any line, then you're most welcome in the comments section below ;)
The problem with your code:
In the for statement, you're using the same variable for both counter and input , i.e., i. This will allow neither for loop to execute properly nor the input to be captured properly.
You're overwriting the i variable everytime you take any input, then only the last input (out of 5 inputs) will be stored in memory.
You're just checking the last input, by using if statement, because the loop is already ended before.
If you want your code to run properly, then these modifications will make that work:
#include<iostream>
using namespace std;
int main()
{
int num,j=0,c=0; // Change the name to num here, because i will be used later as a counter variable.
for(int i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>num;
// Don't end for loop here, this will not allow every input to be checked.
if(num==0)
{
cout<< "0 is not even number"<<endl;
}
else if(num%2==0)
{
j++;
}
else if(num%2 !=0) // Or just add a *else* here instead of *else if*, they will work exactly the same here.
{
c++;
}
} // End of for loop
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Firstly, 0 is an even number, and your code needs to be properly indented, just so you can see that you are indeed reading the input into a single integer, which also controls the loop, and your if statement is outside the for loop (despite the misleading indentation. Here's a simple example implementation, but you can (and should) fix the bugs I pointed out in your own code:
#include <iostream>
int main() {
std::cout << "Enter 5 numbers\n";
int cnt(5);
int n, odd(0), even(0);
while(cnt-- && (std::cin >> n))
n % 2 ? ++odd : ++even;
std::cout << odd << " odd, "
<< even << " even numbers" << std::endl;
return 0;
}
Note the post decrement and the fact the && short-circuits.
This should be your code:
you take an array of integer where you store the input value. Head over to https://www.tutorialspoint.com/cprogramming/c_arrays.htm to learn more abour arrays..
#include<iostream>
using namespace std;
int main(){
int i,j=0,c=0;
int numbers[5];
for(i=0;i<5;i++){
cout<<"enter 5 numbers "<<i ;
cin>>numbers[i];
}
for(i=0;i<5;++i){
if(numbers[i]==0)
{
cout<< "0 is not even number"<<endl;
}
else if(numbers[i]%2==0)
{j++;}
else if(numbers[i]%2 !=0)
{c++;}
}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
using namespace std;
int main()
{
int * Array = new int[5];
int even(0), odd(0);
for(int i = 0; i < 5; i++)
{
cout<<"enter "<< i+1 << "-th number: " << flush;
cin>>Array[i];
if(!Array[i])
{
cout<< "0 is not even number... input again"<<endl;
i = i-1;
}
else
{
if(Array[i]&1) odd++;
else even++;
}
}
cout<<"total exists even : "<<even<<endl;
cout<<"total exists ODD : "<<odd<<endl;
cin.get(); cin.get();
delete[] Array;
return 0;
}

Breaking a loop when entering a specific number?

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

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