So I'm trying to make a program that will separate one array of ints into two, one for even ints, and one for uneven ints. Now, the strange thing is, if I only enter even or uneven numbers into the base array, the program works fine, but if I enter a mix of the two, one of the values held by the two new array will be a random, usually negative, big number, any idea why that is?
#include <iostream>
using namespace std;
void main()
{
int *a, n, *even_nums = 0, *uneven_nums = 0, counter_even = 0,counter_uneven = 0;
cout << "How many values does your array have?\n" << endl;
cin >> n;
a = new int[n];
cout << "\nEnter the values in your array:" << endl;
for (int i = 0; i < n; i++)
{
cout << "a[" << i << "] = ";
cin >> a[i];
if (a[i] % 2 == 0)
counter_even++;
else
counter_uneven++;
}
if (counter_even == 0)
cout << "There are no even numbers in your array." << endl;
else
even_nums = new int[counter_even];
if (counter_uneven == 0)
cout << "There are no uneven numbers in your array." << endl;
else
uneven_nums = new int[counter_uneven];
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
if (counter_even != 0)
{
cout << "\nThe even numbers in your array are:" << endl;
for (int i = 0; i < counter_even; i++)
cout << even_nums[i] << " ";
}
if (counter_uneven != 0)
{
cout << "\nThe uneven numbers in your array are:" << endl;
for (int i = 0; i < counter_uneven; i++)
cout << uneven_nums[i] << " ";
}
system("PAUSE");
}
In
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
You are using the same index for all of the arrays. This will not work as even_nums and uneven_nums will be smaller than a if you have both. You will eventually be writing past the end of the array which is undefined behavior.
What you need to do is add one index for each array and every time you insert an element into the array then you advance that index.
for (int i = 0, u = 0, e = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[e++] = a[i];
else
uneven_nums[u++] = a[i];
}
Also you are using void main() which is not standard and should not be used. int main() and int main(int argc, char** argv) are the standard acceptable signatures of main()
In the block
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
you are using i as the same index for arrays a, even_nums and uneven_nums. You need to use separate indexes for these arrays.
For example, if you have n=10 elements, 5 even and 5 odd, your even_nums and uneven_nums contains only 5 elements each.
Related
I am trying to filter an array given by the user on basis of whether it is positive even, positive odd, negative even, or negative odd.
And, based on this filtration, I am trying to put them in the respected array but my code is working for the 1st part; i.e. it is taking user array but the problem is: It is not entering my filtration code.
The code is here:
#include<iostream>
#include<limits>
#include <functional>
using namespace std;
int main()
{
int n ;
cout<<"\n Enter the size of array :-";
cin>>n;
int numbers[n];
int peven[n],podd[n],neven[n],nodd[n];
for (int i = 0; i < n ; i++){
cout<<"\n Enter value "<<i+1<<" = ";
cin>>numbers[i];
}
cout<<"\n\n";
for (int i = 0; i < n ; i++){
cout<<" "<<numbers[i];
}
cout<<"\n\n";
for(int j = 0;j<n;j++){
if ( ((numbers[j]%2) == 0) && (numbers[j] > 0) ) {
for(int i = 0; i<1; i--){
cin>>peven[i];
i++;
}
}
else if ( ((numbers[j]%2) == 0) && (numbers[j] < 0) ){
for(int i = 0; i<1; i--){
cin>>neven[i];
i++;
}
}
else if ( ((numbers[j]%2) != 0) && (numbers[j] > 0) ){
for(int i = 0; i<1; i--){
cin>>podd[i];
i++;
}
}
else {
for(int i = 0; i<1; i--){
cin>>nodd[i];
i++;
}
}
}
cout<<"\n The +ve even number array is :- "<<peven[n];
cout<<"\n The +ve odd number array is :- "<<podd[n];
cout<<"\n The -ve even number array is :- "<<neven[n];
cout<<"\n The -ve odd number array is :- "<<nodd[n];
return 0;
}
There are several problems in your code. Here is a list (which is not exhaustive) :
it is forbidden to create a constant size array with an integer which is not constant :
cin>>n;
int numbers[n];
As Sam Varshavchik mentioned, it is not possible to finish this loop :
for(int i = 0; i<1; i--)
You have no reason to read value from cin after you fill the array to filter. Line like this one should be modified :
cin>>peven[i];
Here is a correction :
#include <iostream>
#include <vector>
#include<limits>
#include <functional>
using namespace std;
int main()
{
vector<int> peven, podd, neven, nodd;
int n;
cout << "Enter the size of vector :-" << endl;
cin >> n;
vector<int> numbers(n, 0);
for (int i = 0; i < n; i++) {
cout << "Enter value " << i + 1 << endl;
cin >> numbers[i];
}
cout << endl;
cout << "Your vector contains : [";
for (int i = 0; i < n; i++) {
cout << " " << numbers[i];
}
cout << " ]" << endl;
cout << endl;
for (int j = 0; j < n; j++) {
if (((numbers[j] % 2) == 0) && (numbers[j] >= 0)) {
peven.push_back(numbers[j]);
}
else if (((numbers[j] % 2) == 0) && (numbers[j] < 0)) {
neven.push_back(numbers[j]);
}
else if (((numbers[j] % 2) != 0) && (numbers[j] >= 0)) {
podd.push_back(numbers[j]);
}
else {
nodd.push_back(numbers[j]);
}
}
cout << "\n The +ve even number array is : [";
for (int j = 0; j < (int)peven.size(); j++) {
cout << " " << peven[j];
}
cout << "] " << endl;
cout << "\n The +ve odd number array is : [";
for (int j = 0; j < (int)podd.size(); j++) {
cout << " " << podd[j];
}
cout << "] " << endl;
cout << "\n The -ve even number array is : [";
for (int j = 0; j < (int)neven.size(); j++) {
cout << " " << neven[j];
}
cout << "] " << endl;
cout << "\n The -ve odd number array is : [";
for (int j = 0; j < (int)nodd.size(); j++) {
cout << " " << nodd[j];
}
cout << "] " << endl;
return 0;
}
Consider two sets retained in two arrays. Find the union, intersection and difference (relative complement) of the two sets.
I managed to solve the union and the intersection, but the difference is giving me a hard time. Any hints? And if possible, keep it as simple as possible, without functions or more complex aspects, because I'm a beginner and I still have a lot to learn.
Thank you in advance!
#include <iostream>
using namespace std;
int main()
{
int v1[100], v2[100], u[200], intersection[100], d[100];
unsigned int v1_length, v2_length, i, j, OK = 0, union_length;
cout << "Enter the number of elements of the first array:" << " ";
cin >> v1_length;
cout << "Enter the elements of the first array:" << '\n';
for (i = 0; i < v1_length; i++)
cin >> v1[i];
cout << "Enter the number of elements of the second array:" << " ";
cin >> v2_length;
cout << "Enter the elements of the second array:" << '\n';
for (i = 0; i < v2_length; i++)
cin >> v2[i];
//Union
union_length = v1_length;
for (i = 0; i < v1_length; i++)
u[i] = v1[i];
for (i = 0; i < v2_length; i++)
{
int ok = 0;
for (j = 0; !ok && j < v1_length; j++)
if (v1[j] == v2[i])
ok = 1;
if (!ok)
{
u[union_length] = v2[i];
union_length++;
}
}
cout << "The union of the two sets contained in the arrays is: ";
for (i = 0; i < union_length; i++)
cout << u[i] << " ";
cout << '\n';
//Intersection
unsigned int k = 0;
cout << "The intersection of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++)
if (v1[i] == v2[j])
{
intersection[k] = v1[i];
k++;
}
for (i = 0; i < k; i++)
cout << intersection[i] << " ";
cout << '\n';
//Difference
unsigned int l = 0, OK2 = 0;
cout << "The difference of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
{
for (j = 0; j < v2_length; j++)
{
if (v1[i] == v2[j])
OK2 = 1;
if (!OK2)
{
d[l] = v1[i];
l++;
}
}
}
for (i = 0; i < l; i++)
cout << d[i] << " ";
cout << '\n';
return 0;
}
It seems that the intersection is the best place to start. You want the items that only in appear in one of the two arrays, right?
So, for the inner loop, you need to compare all the elements. Then, if no match was found, you have the a unique element.
You need to add the curly braces {} to the for loop. I know that curly braces are distracting at times, but over time, you will probably find it safer to almost always include them to avoid confusion.
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++) {
if (v1[i] == v2[j]){
break; // this item is not unique
} else if(j == v2_length - 1){
d[l] = v1[i]; // This is the unique one, add it to the answer array
l++;
}
}
for (i = 0; i < l; i++)
cout << intersection[l] << " ";
cout << '\n';
You're on the right track!
You're doing a few things wrong. Here are some fixes you can try:
Only set OK2 to 0 once per inner-loop
Reset OK2 to 0 at the end of the inner-loop
Only do the insertion into d after the inner-loop has completed
As an optimization, consider breaking after you set OK2 to 1, as you know at that point it can never be set to 0 for the current value pointed to by the outer-loop.
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;
}
I need to write a program that receives 2 arrays and checks how many times 1 is included in the other...
But I cant find what is wrong with my program! tx!!
#include <iostream>
using namespace std;
int main()
{
int vector1[500];
int vector2[100];
int a = 0, b = 0, count = 0, k = 0;
cout << "enter size of first array:" << endl;
cin >> a;
cout << " enter first array values:" << endl;
for (int i = 0; i < a; i++)
cin >> vector1[i];
cout << "enter size of second array:" << endl;
cin >> b;
cout << "enter secound array values:" << endl;
for (int i = 0; i < b; i++)
cin >> vector2[i];
for (int i = 0; i < b; i++)
for (int j = 0; j < a; j++)
if (vector2[i + k] == vector1[j])
{
count++;
k++;
}
else
k = 0;
cout << count << endl;
system("pause");
return 0;
}
Why at all do you need k? The problem is about all inclusions of all elements right? If O(n^2) complexity is fine, then...
for (int i = 0; i < b; i++)
for (int j = 0; j < a; j++)
if (vector2[i] == vector1[j])
count++;
One obvious disadvantage of the code above is that you'll get the total sum of all occurences of elements from vector1 in vector2. The key idea remains the same in case you need to know, which elements exactly appeared in another array and how many times, you'll just have to use map or other vector.
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;
}