user3047983
user3047983

Reputation: 61

Comparing two arrays in C?

So I have two arrays, a[17] and b[12]. I want to compare the first 12 numbers of each, and if the numbers match have it print out a "0", if they dont match have it print out a "1". But it doesnt work. It should print "000001111111 " but it doesnt. Can anyone please tell me why?

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

int main(){

int i, j;

int a[17] = {1,0,1,0,0,1,0,1,0,1,0,0,0,1,1,0,1};
int b[12] = {1,0,1,0,0,0,1,0,1,0,1,1}; 

for(i=0;i<12;i++)
for(j=0;j<12;j++)
   if(a[i] == b[j])
      printf("1");
   else
      printf("0");


system("pause");
return 0;
}

Upvotes: 1

Views: 142

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

Your code should be:

for(i=0;i<12;i++) {
   if(a[i] == b[i]) {
      printf("1");
   } else {
      printf("0");
   }
}

There is no need of two loops.

You want to compare elements from arrays at same indices, so the indices i should be same for both arrays.

Upvotes: 6

Related Questions