I am new to C language. Suppose I have two arrays a
and b
int a[10] = { 1,2,3,4,5,6,7,8,9,0 };
int b[10] = { 1,3,5,7,9 };
and I want to perform a-b
so that I can get all elements of array a
which are not present in array b
. In ruby or python, I can just simply do a-b
and get the result. Here is my c code that I have tried but my code which is not working.I am looking for a C library that does this operation for me in a line.I have also found this library but not sure how to implement it. Any kind of help is appreciated.
#include<stdio.h>
#define Max 100
int m,n,i,j,k,p,q,r,s;
int flag=1;
char char1,char2,char3;
void Difference(int *,int *,int ,int);
void Display2(char ,char ,int );
int a[10] = { 1,2,3,4,5,6,7,8,9,0 };
int b[10] = { 1,3,5,7,9 };
int c[10];
void Difference(int *a1,int *b1,int m1,int n1)
{
q=0;
p=0;
i=0;
for(k=0;k<m1;k++){
flag=1;
for(j=0;j<n1;j++){
if(b1[j]==a1[k]){
flag=1;
q++;
break;
}
else{
flag=0;
}
}
if(flag==0){
c[p]=a1[k];
p++;
}
}
}
void Display2(char ac,char bc,int m1)
{
printf("\nThe Difference Of Two Sets i.e '%c - %c' Is : { ",ac,bc);
r = m1 - q;
for(p=0;p<r;p++){
printf("%2d",c[p]);
}
printf(" }");
}
int main(){
Difference(a,b,m,n);
Display2('A','B',m);
return 0;
}
I can guess, you forgot to initialize your m
and n
variables with proper values.
Add m = 10; n = 5;
before calling Difference
and your code will work.
I also suggest you to write more readable code: better naming for variables, use some spaces and avoid global variables.
Edit: In C++ you can write:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
int main() {
std::set<int> a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::set<int> b = { 1, 3, 5, 7, 9 };
std::set<int> c;
std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(c, c.begin()));
for (const auto item : c)
std::cout << item << " ";
return 0;
}
Detail information about std::set_difference
can be found here