Vector Appending - c++

so far this is my code what i am trying to do is say the user inputs 1 2 3 and then presses -1, he or she will be asked to input another set of numbers say 9 8 7, what my programs is suppose to do is display them out as such 1 2 3 9 8 7, but rather it is displaying them like this 6 6 6 6 6 6, basically it counts how many numbers there are and displays that amount of numbers with that number. So can anyone help me out here, how do i make it so that it displays the two sets of numbers combined?
#include <iostream>
#include <vector>
using namespace std;
vector<int> append(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> c(n + m);
int i;
for (i = 0; i < n; i++)
c[i] = a[i];
for (i = 0; i < m; i++)
c[n + i] = b[i];
return c;
}
int main()
{
cout << "Please enter a set of numbers, insert -1 when done.\n";
vector<int>a;
bool more = true;
while (more)
{
int n;
cin >> n;
if (n == -1)
more = false;
else
a.push_back(n);
}
cout << "Please enter another set of numbers, insert -1 when done.\n";
vector<int>b;
more = true;
while (more)
{
int m;
cin >> m;
if (m == -1)
more = false;
else
b.push_back(m);
}
vector<int>d = append(a,b);
{
int i;
for (i= 0; i < d.size(); i++)
cout << d.size() << "\n";
}
}

That's because at the end you're printing the size, not the value:
cout << d.size() << "\n";
Should be:
cout << d[i] << "\n";

It is because when you are printing it, you are printing d.size instead of d[i].
cout << d.size() << "\n";
Would needs to be:
cout << d[i] << endl;

Related

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

How to fix addition/multiplication table errors?

I am having troubles with some of the inputs for my addition/multiplication table, and am hoping to find some help towards fixing this. I will begin by posting what I have for the program.
The code is as follows :
#include <iostream>
using namespace std;
void die() {
cout << "BAD INPUT!" << endl;
exit(1);
}
int main() {
const int ADD = 1;
const int MULTIPLY = 2;
const int MAX_SIZE = 20;
int choice = 0, min = 0, max = 0;
cout << "Choose:\n";
cout << "1. Addition Table\n";
cout << "2. Times Table\n";
cin >> choice;
if (!cin) die();
if (choice != ADD and choice != MULTIPLY) die();
cout << "Please enter the smallest number on the table:\n";
cin >> min;
if (!cin) die();
cout << "Please enter the largest number on the table:\n";
cin >> max;
if (!cin) die();
if (min > max) die();
if (max - min >= MAX_SIZE) die();
if (choice == ADD) {
for (int i = 0; i <= max; i++) {
if (i == 0)
cout << '+';
else
cout << i;
cout << '\t';
for (int j = min; j <= max; j++) {
cout << i + j << '\t';
}
cout << '\n';
}
}
if (choice == MULTIPLY) {
for (int i = min; i <= max; i++) {
if (i == min) {
cout << 'X';
else
cout << i;
cout << '\t';
for (int j = min; j <= max; j++) {
cout << i * j << '\t';
}
cout << '\n';
}
}
}
Now, here are the mistakes that I am getting from this code that I cannot seem to resolve. First, when doing the MUlTIPLY table with min = 1, max = 1, I am getting:
X 1
when I should be getting (I believe)
X 1
1 1
Secondly, while doing the MULTIPLY table with min = 1, max = 12, I am getting:
X 1 2 3 4 ... 12
2 2 4 6 8 ... 24
3 3 6 9 12 ... 36
when I should be getting
X 1 2 3 4 ... 12
1 1 2 3 4 ... 12
2 2 4 6 8 ... 24
3 3 6 9 12 ... 36
And finally, when using the ADD table with min = 21, max = 40, I cannot post all of the code since it is such a mess, but basically the columns/rows are as follows:
+ 21 22 23 24 25 ...
5
1
6
2
7
3
8
When obviously, the code should output the rows and columns to be 21 - 40 evenly. As you can see in the last example, my rows are outputting properly, but somehow my columns are a complete, garbled mess.
I have been sitting and staring at this code for awhile, and can't seem to fix these issues at hand. Can anyone help lead me in the right direction? I really appreciate any help and hints :)
Check this out. Might not be fully optimized, but works
if (choice == ADD) {
cout << '+';
for (int i = min; i <= max; i++) {
cout << '\t' << i;
}
for (int i = min; i <= max; i++) {
cout << '\n' << i << '\t';
for (int j = min; j <= max; j++) {
cout << i + j << '\t';
}
}
}
if (choice == MULTIPLY) {
cout << 'X';
for (int i = min; i <= max; i++) {
cout << '\t' << i;
}
for (int i = min; i <= max; i++) {
cout << '\n' << i << '\t';
for (int j = min; j <= max; j++) {
cout << i * j << '\t';
}
}
}
See output here.
#include <iostream>
#include <iomanip>
#include <cstdio>
void die()
{
std::cout << "BAD INPUT!" << "\n";
exit(1);
}
int main() {
const int ADD = 1;
const int MULTIPLY = 2;
const int MAX_SIZE = 20;
int choice = 0, min = 0, max = 0;
std::cout << "Choose:\n";
std::cout << "1. Addition Table\n";
std::cout << "2. Times Table\n";
std::cin >> choice;
if (!std::cin) die();
if (choice != ADD and choice != MULTIPLY) die();
std::cout << "Please enter the smallest number on the table:\n";
std::cin >> min;
if (!std::cin) die();
std::cout << "Please enter the largest number on the table:\n";
std::cin >> max;
if (!std::cin) die();
if (min > max) die();
if (max - min >= MAX_SIZE) die();
if (choice == ADD) {
for (int i = 0; i <= max; i++) {
if (i == 0)
printf(" +");
else
printf("%3d", i);
printf(" ");
for (int j = min; j <= max; j++) {
printf("%3d ", i + j);
}
printf("\n");
}
}
if (choice == MULTIPLY) {
/* for printing header of the multiplication table */
std::cout << "X\t";
for (int j = min; j <= max; j++) {
std::cout << min * j << "\t";
}
std::cout << "\n";
/* for printing rest of the table */
for (int i = min; i <= max; i++) {
std::cout << i << "\t";
for (int j = min; j <= max; j++) {
std::cout << i * j << '\t';
}
std::cout << '\n';
}
}
}
The crucial mistake in your code for multiplication was that, you were trying to print (max - min + 1) + 1 rows in total, the extra +1 for the header. While your code was printing the first row as header and then starting directly with the second row.
Your code for addition table was correct, but 21 to 40 with tab character in between was too taking too much space for a typical laptop screen, not to say the output won't be pretty.
On my system, the output of tput lines and tput cols was 38 and 144 resp.
which wasn't sufficient for your code.
you can format the output with printf using printf fixed width output.
Considering you are not much familiar with C++, I would like to state that
using the std namespace as default namespace will work for this program, but when you working with larger projects, you should always prefix it.
I haven't enough reputation to add comment
if I were, I was commenting these lines
if (i == min) {
cout << 'X';
else
cout << i;
cout << '\t';

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

The difference between 2 arrays in c++ A\B

So I have 2 arrays. Let's say the first one it's called a and the second one b. The first one uses "i" for it's elements and the second one uses "j".
For example we have a[ 1 2 3 4] and b[3 4 5] it should show c[1 2]. In the array c I want to show the elements that are in a and aren't in b.
This is what I've tried, but without succes:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[50], b[50], c[50], i, j, k, n, m;
cout << "n= "; cin >> n;
//Read arrays
for (i = 0; i < n; i++) {
cout << "a[" << i << "]: "; cin >> a[i];
}
cout << "\nm= "; cin >> m;
for (j = 0; j < m; j++) {
cout << "b[" << j << "]: "; cin >> b[j];
}
//Show the arrays
cout << endl;
cout << "\na[ ";
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "]";
cout << endl;
cout << "\nb[ ";
for (j = 0; j < m; j++) {
cout << b[j] << " ";
}
cout << "]";
//Calculate the difference
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j])
c[k] = a[i];
k++;
while (j == m && i < n)
i++;
}
//Show the difference array
cout << endl;
cout << "\nc[ ";
for (i = 0; i < k; i++) {
cout << c[i] << " ";
}
cout << "]";
return 0;
}
If the items are sorted, use std::set_difference:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
int a[] = { 1, 2, 3, 4 };
int b[] = { 3, 4, 5 };
std::vector<int> cv;
std::set_difference(std::begin(a), std::end(a),
std::begin(b), std::end(b),
std::back_inserter(cv));
for (auto& s : cv)
std::cout << s << "\n";
}
Output:
1
2
The advantage of using the STL algorithms is that the purpose of the code is known immediately just by looking at the name of the function, and that they work every time (if you give them the correct parameters). Note the lack of comments -- any competent C++ programmer understands right away what's being done.
On the other hand, if you didn't mention what your original code was trying to do (including removing the comments), it would take much more effort to figure out what it's supposed to be doing, and as you've seen, it contains bugs.
Your logic is wrong.
Explanation
So the thing that we will do
For each element in a we will have to check if it is there in array b or not.
If we see any element of a[i] in b[1..m] then we can't add it to c.
So in code we just mark it by f=1
When I get out of that second for loop I want to check if that a[i] is eqaul to any of the element in b[1..m] in which case f will be 1. But if it is 0 then add it to array c[].
Correct one
int k=0;
for(int i=0;i<n;i++)
{
int f=0;
for(int j=0;j<m;j++)
if(a[i]==b[j])
f=1;
if(!f)
c[k++]=a[i];
}
Where OP went wrong?
Being not equal to one element of b[] doesn't guarantee that the element is not appearing b[0..m-1] . This is where op went wrong.
In the for loop
for(j=0;j<m;j++) you are checking if particular a[i] is equal to b[j] or not. If that is the case then it is added to c[] . It is wrong. Also i is not incremented in the loop unless j==m and as in the for loop the condition is j<m so i is never incremented. And k is incremented every time so not every element in c is valid they may contain garbage value even after processing.
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j]) // this doesn't mean that it is not appearing in `b`
c[k] = a[i];
k++; // k is incremented in every iteration which is wrong. It should be only when we are sure that `a[i]` is not in `b[0..m-1] `
while (j == m && i < n)
i++; // OP is not using it anywhere...this is redundant.
}
what op did?
Compared first element of a[0] with every element of b[0..m-1] and array c[] contains m elements irrespective of what a[] and b[] is, out of which
c[i]={ a[0] if b[j]==a[0]
{ garbage value if b[j] not equal to a[0]
Dry Run of OP's code
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j])
c[k] = a[i];
k++;
while (j == m && i < n)
i++;
}
Input
Case: 1 2 3 4 :a[]
2 3 4 1 :b[]
Step 1: i=0 a[0]!=b[0] is true so c[0]=a[0]. the `while loop` not entered.
j++
Step-2: i is still 0. a[0]!=b[1] so it is added c[1]=a[0]. While loop not entered.
j++
Step-3: i is still 0. a[0]!=b[2]. So c[2]=a[0]. While loop skipped.
j++
Step-4: i is still 0. a[0]==b[3] is true so no assignment done. But k is incremented. so c[3]=garbage. j=3 so while loop skipped
j++
Out of for loop.
Output: [here x is garbage value]
a[]: 1 2 3 4
b[]: 2 3 4 1
c[]: 1 2 3 x
Example test case
1 2 3 4 :=a
2 3 4 1 :=b
Corrected Code
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[50], b[50], c[50], i, j, k, n, m;
cout << "n= "; cin >> n;
//Read arrays
for (i = 0; i < n; i++) {
cout << "a[" << i << "]: "; cin >> a[i];
}
cout << "\nm= "; cin >> m;
for (j = 0; j < m; j++) {
cout << "b[" << j << "]: "; cin >> b[j];
}
//Show the arrays
cout << endl;
cout << "\na[ ";
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "]";
cout << endl;
cout << "\nb[ ";
for (j = 0; j < m; j++) {
cout << b[j] << " ";
}
cout << "]";
//Calculate the difference
k = 0; i = 0;
int k=0;
for(int i=0;i<n;i++)
{
int f=0;
for(int j=0;j<m;j++)
{
if(a[i]==b[j])
f=1;
if(!f)
c[k++]=a[i];
}
}
//Show the difference array
cout << endl;
cout << "\nc[ ";
for (i = 0; i < k; i++) {
cout << c[i] << " ";
}
cout << "]";
return 0;
}
Your code seems to check if the elements in a are equal to all elements of b. If you just want to check the elements in a if they are equal to at least one element of b, you can do
for (int i=0; i<n; i++) {
bool found = false;
for (int j=0; j<m; j++) {
if (a[i] == b[j]) {
found = true;
break;
}
}
if (!found) {
std::cout << "a["<<i<<"] is not in b"<<std::endl;
}
}
Or add the element to c, but I would recommend to use std::vector<int> c for that.
In the array c I want to show the elements that are in a and aren't in b
It seems like you are looking for std::set_difference
int a[4] = {1, 2, 3, 4}, b[3] = {3, 4, 5};
int c[2] = {}; // declare c with enough space to hold all the elements in result
std::set_difference(a, a + 4, b, b + 3, c); // now c contains the element that are in a but not in b
You can do this very easily using 'set'.
#include<iostream>
#include<set>
int main(){
std::set<int> a = {1,2,3,4} , b = {3,4,5};
for(int const inB : b)
a.erase(inB);
for(int const inA : a)
std::cout << inA << " ";
std::cout << std::endl;
return 0;
}

How to count how many times each number has been encountered?

I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}