output different elements from two arrays - c

I am trying to output different elements from two arrays. So if i have an array A: {9, 0, 1} and B is {0, 8, 1}, I need to output an element which included in the first set, but are not included in the second :9 Can not think how I should compare all elements from the first array with the second one.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10],b[10],c,n,i,j;
printf("enter a number: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter a[%d]: ",i+1);
scanf("%d",&a[i]);
}
printf("\n");
for(j=0;j<n;j++){
printf("Enter b[%d]: ",j+1);
scanf("%d",&b[j]);
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]); }
printf("\n");
for (i = 0; i < n; i++) {
printf("%d ", b[i]); }
printf("\n");
return 0;
}
I'd like to show my thoughts but i think it's stupid:
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(a[i]!= b[j]){
c=a[i];
}
}
printf("%d ",c);
}

This can be easily solved using Binary search. Follow the simple steps.
Step 1: Sort the second array.
Step 2: For each element of the first array, binary search it in the second array, if its not present , print it, otherwise dont.
The time complexity is O(m log n), where m is length of first array and n is length of second array.

If you want a more efficient solution, as suggested by #Sumeet Singh, you can sort the second array with qsort, then find similar elements from the first array with bsearch(binary search).
Your current solution is O(N^2) time, which will be very slow with large n, but you can achieve more efficiency with this approach.
Here is some code I wrote up with demonstrates this:
#include <stdio.h>
#include <stdlib.h>
#define NNUMBERS 10
void get_array_input(int array1[], int array2[], size_t *n);
void search_elements(int array1[], int array2[], size_t n);
void print_arrays(int array[], size_t n);
int cmp_func(const void *a, const void *b);
int main(void) {
int array1[NNUMBERS], array2[NNUMBERS];
size_t n;
/* input from user */
get_array_input(array1, array2, &n);
printf("\nFirst array: ");
print_arrays(array1, n);
printf("\nSecond array: ");
print_arrays(array2, n);
/* sorting the second array */
qsort(array2, n, sizeof(*array2), cmp_func);
printf("\nSorted Second array: ");
print_arrays(array2, n);
/* the search begins */
search_elements(array1, array2, n);
return 0;
}
void get_array_input(int array1[], int array2[], size_t *n) {
size_t i;
printf("Enter n: ");
if (scanf("%zu", n) != 1) {
printf("Invalid n value.\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < *n; i++) {
printf("Enter array1[%zu]: ", i);
if (scanf("%d", &array1[i]) != 1) {
printf("Invalud array value.\n");
exit(EXIT_FAILURE);
}
}
for (i = 0; i < *n; i++) {
printf("Enter array2[%zu]: ", i);
if (scanf("%d", &array2[i]) != 1) {
printf("Invalud array value.\n");
exit(EXIT_FAILURE);
}
}
}
void search_elements(int array1[], int array2[], size_t n) {
size_t i;
void *key;
printf("\nElements in first array which are not in second array: ");
for (i = 0; i < n; i++) {
key = bsearch(&array1[i], array2, n, sizeof(*array2), cmp_func);
if (!key) {
printf("%d ", array1[i]); /* not found, so print it */
}
}
printf("\n");
}
void print_arrays(int array[], size_t n) {
size_t i;
for (i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
/* cmp function needed for qsort and bsearch */
/* many ways to write these */
int cmp_func(const void *a, const void *b) {
const int *num1 = (const int *)a;
const int *num2 = (const int *)b;
if (*num1 > *num2) {
return +1;
} else if (*num1 < *num2) {
return -1;
}
return 0;
}
Input:
Enter n: 3
Enter array1[0]: 9
Enter array1[1]: 0
Enter array1[2]: 1
Enter array2[0]: 0
Enter array2[1]: 8
Enter array2[2]: 1
Output:
First array: 9 0 1
Second array: 0 8 1
Sorted Second array: 0 1 8
Elements in first array which are not in second array: 9

You are on the right path. You are taking each value from the first array and comparing to each value in the second.
What you need to do now is to only print a[i] if there isn't any b[j] such that they are the same. The easiest way is to set a flag (say, unique=1). You can give this flag any name you find suitable, but in this case I'm thinking it says that the number a[i] is "unique" to the array a. So in this case you start with the premise that, yes, you won't find a[i] in the arrayb, and then you try to disprove your assumption. If at any time of you search you find an instance of a[i] == b[j], then your premise was wrong, so you set unique=0.
After you have compared this a[i] against all elements in b, you review your flag. And you print the appropriate message depending on whether you found this element in b or not.
Note that this assumes that the same value doesn't appear twice in a.

I have edited your code a little bit and this code gives you desired output:
#include <stdio.h>
int main(void){
int a[10],b[10],c,n,i,j;
int counter=0;
printf("enter a number: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter a[%d]: \n",i+1);
scanf("%d",&a[i]);
}
printf("\n");
for(j=0;j<n;j++){
printf("Enter b[%d]: \n",j+1);
scanf("%d",&b[j]);
}
for(i=0;i<n;i++){
counter=0;
for(j=0;j<n;j++){
if(a[i]!=b[j]){
counter++;
}
}
if(counter == n){
printf("%d ",a[i]);
}
}
return 0;
}
Let's explain this code a little bit:
In the last nested for loop, outer loop takes one element from array a. Inner loop gets every element of array b in order to compare it to taken element from array a. If none of the elements of array b is equal to a's taken element, counter will be equal to n(array size). Then we can print this element taken from a(it means there is no match between this taken element and array b's all of elements.

Related

Adding the same number multiple times to an empty array in C

This is a piece of code to add the same number multiple times to an empty array but when I am printing the now non empty array, I am getting some other values:
#include<stdio.h>
#include<stdlib.h>
void sort_0(int arr[100], int i, int n){
int final_array[100], c=0;
// Count the number of '0' in the array
for(i=0;i<n;i++){
if(arr[i] == 0){
c++;
}
}
// Add the c number of '0' to the final_array
for(i=0;i<c;i++){
scanf("%d",final_array[i]);
}
for(i=0;i<c;i++){
printf("%d ", final_array[i]);
}
}
int main(){
int arr[100], i, n;
// Entering the size of the array
scanf("%d", &n);
// Entering n elements into the array
for(i=0;i<n;i++){
scanf("%d", &arr[i]);
}
sort_0(arr,i,n);
return 0;
}
In the above code, the number of times 0 appears in the array is counted. Then the count is taken as the range and 0 is adding to the empty array final_array count times.
If c = 5, the final_array = {0,0,0,0,0}
Expected Output:
arr = {0,1,4,3,0}
Output = 2
I am not getting any output
Since you don't know how much 0 you'll need to add to your array_final I figured out that a better solution could be to create that array after you have the number of 0 of the first array. Also, I see no reason why you were passsing i to the function since you can simply define it in the function itself.
void sort_0(int arr[10], int n, int* c){
int i;
for(i=0;i<n;i++){
if(arr[i] == 0){
(*c)+= 1;
}
}
}
int main (void) {
int size;
printf("Enter array size: ");
scanf("%d", &size);
int arr[size];
for (int i=0;i<size;i++) {
scanf("%d",&arr[i]);
}
int c = 0;
sort_0(arr, size, &c);
printf("C is: %d\n",c);
int* final_array;
if ((final_array=malloc(c * sizeof(int)))==NULL) // should always check malloc errors
{
perror("malloc");
return -1;
}
for (int i=0;i<c;i++) {
final_array[i]= 0;
}
printf("{");
for (int i=0;i<c-1;i++) {
printf("%d,", final_array[i]);
}
printf("%d}\n",final_array[c-1]);
return 0;
}

How to get the sum of two index in an array in C?

Im making a code for an array that has a dynamic size and filling the array manually.Then, it will print. It will also ask for a number and finding the index that is equal to the two indexes.
I using codeblocks for this code. Id tried for loop to find the two indexes that is eqaul to the inputed number.
#include <stdlib.h>
#include <stdio.h>
void printArray(int *array, int size) {
printf("[");
for (int i = 0; i < size - 1; i++) {
printf("%i,", array[i]);
}
if (size >= 1)
printf("%i", array[size-1]);
printf("]\n");
int num;
printf("Enter number to be calculate: ");
scanf("%d",num);
for(int i= 0; i < size - 1; i++){
if (array[i] + array[size-1] == num){
printf("%d %d", array[i],array[size-1]);
}
size--;
}
}
int main(void) {
int count;
int num;
int sum;
printf("Enter the size of the array:\n");
scanf("%d", &count);
int *array = malloc(count * sizeof(*array));
if (!array) {
printf("There was a problem you entered");
exit(EXIT_FAILURE);
}
printf("Enter the elements of the array:\n");
for (int i = 0; i < count; i++)
scanf("%d", &array[i]);
printArray(array, count);
}
I expect the output:
Index 1 and 5 are eqaul to the inputed number.
but it gives error.
To begin with, the following bug is one of the problem -
scanf("%d",num);
should be -
scanf("%d", &num);
The final loop in printArray is basically iterating through the array one element both upwards & downwards at the same time.
So, for n=6, if sum of either (a[0]+a[5]), (a[1]+a[4]) or (a[2]+a[3]) does not equal the required number , it would show up as unmatched.
This loop should be replaced by a nested loop so that inner loop iterates from j=i+1 to size-1 to allow check for a[i]+a[j] == num for all possible permutations of array indexes.

remove duplicate element from array in c, can't modify a variable

Hi i was wondering why i can't manage to change the value of the variable "cinter" in this:
int nbobject=7, cinter, i, *inter;
printf("\nHow many elements in array :");
scanf("%d", &cinter);
inter=malloc(nbObject*sizeof(int));
printf("\nEnter the elements :");
for(i=0;i<cinter;i++){
scanf("%d",&inter[i]);
}
qsort(inter, cinter, sizeof *inter, compare);
noDuplicate(inter, cinter);
cinter=noDuplicate(inter,cinter);
for(i=0;i<cinter;i++){
printf("%d", inter[i]);
}
printf("\nNumber of elements in array : ");
printf("%d", cinter);
printf("\nArray elements : ");
for (i=0;i<cinter;i++){
printf("%d ", inter[i]);
}
int noDuplicate( int arr[],int size ){
int i=0, j=0;
for (i = 1; i < size; i++){
if (arr[i] != arr[j]){
j++;
arr[j] = arr[i]; // Move it to the front
}
}
// The new array size..
size = (j + 1);
return size;
}
So what i did is simply sort the array and remove the duplicate. I'd like for the variable "cinter" that's number of elements in the array to be reduced by the number of removed elements so that i can use it later on to know how many relevant elements are in the array but no matter what i always end up with the same number in the end.
Output :
How many elements in array : 6
Enter the elements : 2 1 2 3 5 1
Number of elements in array : 6
Array elements : 1 2 3 5 3 5
EDIT : #Arash here's a code you can run, all i need is to be able to change the value of cinter while i delete duplicates so i can use it later to know exactly how many relevant items are in my array.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
static int compare (void const *a, void const *b){
int const *pa = a;
int const *pb = b;
return *pa - *pb;
}
void main(){
int nbObjets=7, *inter;
size_t cinter;
size_t i, j;
printf("\nHow many elements in the array :");
scanf("%d", &cinter);
inter=malloc(nbObjets*sizeof(int));
printf("\nEnter the elements :");
for(i=0;i<cinter;i++){
scanf("%d",&inter[i]);
}
qsort(inter, cinter, sizeof *inter, compare);
noDuplicate(inter, cinter);
cinter=noDuplicate(inter, cinter);
printf("\nNumber of elements in the array (cinter) : ");
printf("%d", cinter);
printf("\nArray elements : ");
for (i=0;i<cinter;i++){
printf("%d ", inter[i]);
}
}
int noDuplicate( int arr[], size_t size ){
size_t i=0, j=0;
for (i = 1; i < size; i++){
if (arr[i] != arr[j]){
j++;
arr[j] = arr[i]; // Move it to the front
}
}
// The new array size..
size = (j + 1);
return size;
}
EDIT : I got it to work by making the changes that Arash told me to do, thanks for the help guys !
You can use pass by address to fix the problem:
void noDuplicate( int arr[],size_t *size ){
size_t i=0, j=0;
for (i = 1; i < *size; i++){
if (arr[i] != arr[j]) {
j++;
arr[j] = arr[i]; // Move it to the front
}
}
// The new array size..
*size = (j + 1);
}
Then you call it this way:
noDuplicate(inter, &cinter);
You try to return the new size at the end in a void function. And the compiler doesn't complain? Make it int (and, btw, not size_t).
int noDuplicate( int arr[],size_t size )
{
(BTW: Throwing such an unformatted code in a Q is not very helpful.)
Of course in your main() you should assign the return value to cinter or whatever.
cinter = noDuplicate(inter, cinter);

Reverse array with recursion in C programming

I was having some problem when trying to do a reverse array using recursion. Here is the function prototype:
void rReverseAr(int ar[ ], int size);
And here is my code:
int main()
{
int ar[10], size, i;
printf("Enter array size: ");
scanf("%d", &size);
printf("Enter %d numbers: ", size);
for (i = 0; i<size; i++)
scanf("%d", &ar[i]);
rReverseAr(ar, size);
printf("rReverseAr(): ");
for (i = 0; i<size; i++)
printf("%d ", ar[i]);
return 0;
}
void rReverseAr(int ar[], int size) {
int start = 0, end = size - 1, temp;
if (start < end) {
temp = ar[start];
ar[start] = ar[end];
ar[end] = temp;
start++;
end--;
rReverseAr(ar, size - 1);
}
}
The expected output should be when user entered 1 2 3 and it supposed to return 3 2 1. However, with these code, the output that I am getting is 2 3 1.
Any ideas?
Your code is almost right. The only problem is that instead of "shrinking" the array from both sides, you shrink it only from the back.
The recursive invocation should look like this:
rReverseAr(ar + 1, size - 2);
You do not need to increment start or decrement end, because their values are not used after modification.
A Simple way :
#include<stdio.h>
using namespace std;
void revs(int i, int n, int arr[])
{
if(i==n)
{
return ;
}
else
{
revs(i+1, n, arr);
printf("%d ", arr[i]);
}
}
int main()
{
int i, n, arr[10];
scanf("%d", &n);
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
revs(0, n, arr);
return 0;
}
Iterate array with recursion in C : link
What you are doing is to exchange values of the 1st and last elements and do the recursion.
Every time you should move your address to the next element as the starter for the next array exchange.
A possible way:
void rReverseAr(int ar[], int size){
int buffer=ar[0];
ar[0] = ar[size-1];
ar[size-1] = buffer;
if ((size!=2)&&(size!=1)) rReverseAr(ar+1,size-2);
}

How to get each element of a array from user input then pass it to a function in another file in C

How can I get each element of an array from user input then pass it to a function in another file. I'm having trouble and need help please. This my code.
main.c
#include <stdio.h>
#include "lab8.h"
int x[100];
int y[100];
int main(void) {
int count, i, product;
printf("Enter the length of both arrays\n");
scanf("%d", &count);
printf("Enter the first array's elements\n");
for(i=0; i<count; i++){
scanf("%i", &x[i]);
}
printf("Element: %i\n", x[i]);
printf("Enter the second array's elements\n");
for(i=0; i<count; i++){
scanf("%i", &y[i]);
}
product = inner_product(x, y, count);
printf("Inner product: %i\n", product);
return(0);
}
lab8.c
#include <stdio.h>
#include "lab8.h"
int inner_product(int a[], int b[], int count) {
int i;
int result = 0;
for( i=1; i<count; i++) {
result = result + (a[i] * b[i]);
}
return result;
}
It only seems to multiply the last element entered for both arrays heres the output.
Enter the length of both arrays
2
Enter the first array's elements
1
2
Element: 0
Enter the second array's elements
3
3
Inner product: 6
The problem is that you are iterating from 1 and you should iterate from 0, in the inner_product() function
for( i=1; i<count; i++) {
/* ^ this should be 0 */
also, don't use global variables specially because you got the rest of it right, you are passing the arrays as arguments to the inner_product() function.

Resources