Home > Blockchain >  compere 2 arrays (numbers)
compere 2 arrays (numbers)

Time:10-31

am trying to compere 2 arrays formed from numbers this is the code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
    int n,i,j,k;
    int a[n];
    int b[n];
    int ta=sizeof(a);

    printf("Enter la taille du tableux: ");
    scanf("%d", &n);
// taking input a
    printf("Enter %d nombres: ",n);
    for(i = 0; i < n;   i)
    {
        scanf("%d", &a[i]);
    }
// taking input b
    printf("Enter %d nombres: ",n);
    for(j = 0; j < n;   j)
    {
        scanf("%d", &b[j]);
    }
//a to b
    for(k=0;k<ta;k  )
    {
        if(a[k] != b[k])
        {
            printf("Is ne sont pas identiques.\n");
            exit(0);
        }
        else if(k == n-1)
        {
            printf("Ils sont identiques.\n");
        }
    }
}

but am not getting the comparation after inserting the arrays, what am i doing wrong.

but am not getting the comparation after inserting the arrays, what am i doing wrong.

CodePudding user response:

When you compare the array a and array b, you are taking incorrect array size.

int ta=sizeof(a);

Below code is give you expected output

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
 {
    int n,i,j,k;
    int a[n];
    int b[n];
    //int ta=sizeof(a) calculate of array size is not correct

    printf("Enter la taille du tableux: ");  //Enter the array size
    scanf("%d", &n);

// taking input a
    printf("Enter %d integers: ",n);
    for(i = 0; i < n;   i)
    {
    scanf("%d", &a[i]);
    }



// taking input b
    printf("Enter %d nombre: ",n);
    for(j = 0; j < n;   j)
    {
    scanf("%d", &b[j]);
    }

//a to b
    for(k=0;k<(sizeof(a)/sizeof(a[0]));k  )
    {
        if(a[i] != b[i])
        {
            printf("are not identical\n");
            exit(0);
        }
    }
    printf("they are identical\n");
}

Output:

Enter la taille du tableux: 3
Enter 3 integers: 1
2
3

Enter 3 nombre: 1
2
3

they are identical

CodePudding user response:

There is one small issue with your code, otherwise it is correct.
Change this:

int n,i,j,k;
int a[n]; // n is not initialized
int b[n];
int ta=sizeof(a);

printf("Enter la taille du tableux: ");
scanf("%d", &n);

To this:

int n,i,j,k;
int ta = sizeof(a);

printf("Enter la taille du tableux: ");
if (scanf("%d", &n) != 1) { /* handle errors */ }
int a[n]; // now n is initialized
int b[n];

The problem is, that n is declared, but never assigned at first. That means, that n can be whatever value was at this memory before. This is called uninitialized memory. Here is a quick demonstration on that:

int main() {
    int arr[256];
    for (int i = 0; i < 256; i  ) {
        printf("d%c", arr[i], (i   1) % 16 == 0 ? '\n' : ' ');
    }
}
  • Related